I know we can not assign a char array to another char array like:
char array1[] = "Hello";
char array2[] = "Hi!";
array1 = array2;//does not compile
But:
char array1[] = "Hello";
char *array2 = NULL;
array2 = array1; //compile
printf("%s", array2); //display Hello
This works.
Can anyone please explain why?
Thanks!
Plain arrays are not assignable. That is why the first code sample doesn't work.
In the second sample, array2
is just a pointer, and array1
, despite being an array, can decay to a pointer to its first element in certain situations. This is what happens here:
array2 = array1;
After this assignment, the pointer array2
points to the first element of the array array1
. There has been no array assignment, but, rather, pointer assignment.
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