Ahmad Humayun said:
Whats the difference between:
char str1[] = "wxyz";
char* str2 = "abcd";
I can do this:
str2 = str1
but I can't do this:
str1 = str2
(isn't str1 technically a pointer?)
No. 'str1' is an array of 5 chars, initialized to the characters
'w', 'x', 'y', 'z' and '\0'. Only if 'str1' is used in a place
where a value is required (e.g. if 'str1' is an argument of a
function call) it gets replaced automatically by a pointer to
the first element of that array. But that doesn't change any-
thing about the "nonpointerness" of 'str1', it's an array and
remains to be an array until it goes out of scope.
In contrast, 'str2' is a pointer, initialized to point to the
string literal "abcd" (that could very well be in read-only
memory). Since 'str2' is a pointer you can assign it a different
value, e.g. by using
str2 = str1;
This works because in this case on the right hand side of the
asignment a value is required and now "the rule" applies, i.e.
that if an array is used in a context where a value is needed
it is replaced by a pointer to its first element.
This automatic conversion is actually not much different from
what happens when you write
int a = 1.2;
Since on the right hand side an int value is required the double
value you have there is automatically converted to an int value.
C could in principle refrain from doing such automatic conversions
and require that you explicitely state your intent like
int a = ( int ) 1.2;
or
str2 = &str[ 0 ];
but that's not how the inventors of C decided to do it and in-
stead introduced some automatic conversions.
But
str1 = str2;
is still a syntax error since 'str1' is not a pointer and can't
be treated like a pointer because it has a completely different
type.
Regards, Jens