Was trying to brush up my C concepts and now it seems all jumbled up :( in pointers, of course
This way of assigning arr to ptr works since we say arr[] will decay to *arr
int arr[] = {1, 2, 3};
int *ptr = arr; // Access arr with ptr
But directly assigning the array to *ptr doesn't work
int *ptr = {1, 2, 3};
printf("%d\n", ptr[0]); // Segmentation fault
My understanding is that int arr[] = {} has a special meaning where a contiguous chunk of stack space is allocated and is directly referred to by the name arr
Trying to do the same thing with int *ptr = {} is just confusing the compiler ??
{1, 2, 3}does not mean “an array”. In a declaration, it is a list of initial values for some object with multiple parts.In
int arr[] = {1, 2, 3};,{1, 2, 3}is a list of three values to use to initialize the arrayarr.In
int *ptr = {1, 2, 3};,{1, 2, 3}would be a list of three values to use to initialize the pointerptr. Butptrdoes not have multiple parts. All it has is one value, a memory address. So{1, 2, 3}would provide1to initialize the address, which is a problem because1is anint, not an address, so the compiler should issue a diagnostic message for that. And there is nothing for2or3to initialize, so the compiler should issue a diagnostic message for that.You can use a compound literal to create an unnamed array directly in source code. A compound literal has the form
(type) { initial values }. So you can create an array ofintwith(int []) {1, 2, 3}.You can declare a pointer and initialize it to point to an array by using a compound literal as the initial value:
(Note that the array is automatically converted to a pointer to its first element, so
ptris initialized to that address.)