I have a variable that needs to hold a pointer to an array. Normally this is done by first creating a variable with the array, then saving the pointer to that variable. However, I need to do this for maybe 10 variables, and I don't want to have to create an extra array for each of them. What I first tried was
int *numList = {1, 2, 3};
But that tries to create an array of pointers to integers. I think the following has the correct type for the list, but I don't know how to cast the array to a pointer.
int (*numList)[3] = {1, 2, 3};
The pointer amount is initialized to point to total : double time, speed, *amount = &total; The compiler converts an unsubscripted array name to a pointer to the first element in the array. You can assign the address of the first element of an array to a pointer by specifying the name of the array.
A pointer can also be initialized to null using any integer constant expression that evaluates to 0, for example char *a=0; .
It is necessary only when you expect it to have a default value. As pointers, just like other variables will hold garbage value unless it is initialized.
So, no. You can't avoid "initializing" an array.
In C99 and C11, you can use a compound literal to achieve what is requested in the question title, namely initialize a pointer so it points to an array literal without any extra variables:
int *numList = (int []){ 1, 2, 3 };
The array that numList
points to has the same scope and lifetime as the pointer itself — it lasts for the block it is defined in if it is inside a function, or for the duration of the program if it is outside any function.
If you were so misguided as to create static int *numList = (int []){ 1, 2, 3};
inside a function, you'd be setting yourself up for a world of hurt — don't do it. (At file scope, outside any function, it doesn't present any problem.) The pointer would be initialized no later than when the function is first called, but there's no guarantee that what it points to has static
duration and subsequent calls could be pointing at garbage.
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