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.
The following code 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.
The remaining array elements will be automatically initialized to zero. If an array is to be completely initialized, the dimension of the array is not required. The compiler will automatically size the array to fit the initialized data.
The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.
Initializing arrays This means that none of its elements are set to any particular value; their contents are undetermined at the point the array is declared. int foo [] = { 16, 2, 77, 40, 12071 }; After this declaration, array foo would be 5 int long, since we have provided 5 initialization values.
Initializing an array in Java involves assigning values to a new array. Java arrays can be initialized during or after declaration. In Java, arrays are used to store data of one single type.
Initializers do not return anything per se. They give the compiler directions as to what to put into the item being declared - in this case, they tell the compiler what to put into elements of an array.
That is why you cannot assign an initializer to a pointer: an array initializer needs to be paired with an array to make sense to the compiler.
A pointer can be initialized with a pointer expression. That is why the initialization in your
char *char_ptr_2 = char_array;
declaration works: the compiler converts char_array
to a pointer, and initializes char_ptr_2
with it.
it's called array initializer, because it initalizes an array and not a pointer.
It's simply C syntax, why the pointer option is not allowed.
They are array initializers, not normal expressions that have a value. I. e., an array initializer can only be used to initialize an array. It is a special bit of syntax for a specific use, end of the story.
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