Why is this right ?
#include<iostream>
using namesp开发者_开发问答ace std;
int main()
{
char *s="raman";
char *t="rawan";
s=t;
cout<<s;
return 0;
}
But this is wrong?
#include<iostream>
using namespace std;
int main()
{
char s[]="raman";
char t[]="rawan";
s=t;
cout<<s;
return 0;
}
In the first example, s=t
does a pointer assignment. In the second, s=t
tries to assign a pointer value (resulting from the implicit conversion, or "decay", of the array expression t
) to an array object. C++ doesn't permit array assignments.
C and C++ happen to be very similar in this area; section 6 of the comp.lang.c FAQ covers the relationship between arrays and pointers very well.
The first example assigns an pointer to another which is valid.
The second example assigns an array to another array which in not allowed in C & C++ both.
This excellent C++ FAQ entry and this answer should be a good read for you.
In addition to what the other guys said:
Contrary to popular belief, arrays are actually not pointers. They just share a lot of similarities when working with them and have a couple of implicit conversions to pointers which is why it's easy to work with them as if they are pointers.
Arrays are a standalone feature of (C and) C++. It doesn't behave exactly like a pointer would.
For example, it's possible to allocate array objects on the stack, which is not possible when you allocate objects using new (which returns a pointer) and pointers.
And the example that you showed is another one: You can't use arrays as if they are pointers. But you can use pointers to point to a continuous piece of memory (array).
Array name is a const pointer. meaning, when you declare an array, the name is a pointer, which cannot be altered.
char *s
means:
address and value both are not constant.
const char *s:
value is constant, not address.
const char * const s;
address and value both are constant.
char *s[]
is an array. Array base address is always contant. You can not change the base address of it, that is not allowed in c.
精彩评论