What do array initialisers such as { 'a', 'b', 'c' }
return? My understanding is that using an initialiser allocates contiguous memory blocks and return the address to the first block.
However, the following code below doesn't work:
char *char_ptr_1 = { 'a', 'b', 'c', '\0' };
On the other hand, this is seems to work fine:
char char_array[] = { 'a', 'b', 'c', '\0' };
char *char_ptr_2 = char_array;
char_array
stores the address to the first memory block which explains why I am able to assign the value of char_array
to chat_ptr_2
. Does C convert the value returned by the initialiser to something which can be stored in a pointer?
I did look online and and found a couple of answers which talked about the difference between arrays and pointers but they didn't help me.
char *char_ptr_2 = (char[]){ 'a', 'b', 'c', '\0' };
– BLUEPIXY 10 hours agochar *char_ptr_1 = "abc";
. However, GCC reports it as deprecated without aconst
modifier. Presumably that is because the compiler is not required to create a unique array for each string literal occurrence. – Theodore Norvell 5 hours ago