Why is this right ?
#include<iostream>
using namespace 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With