I'm trying to understand the difference between these two pieces of code in C:
int array[] = { 1, 2, 3 }; // init a regular array
int *numList = {1, 2, 3}; // init an array of pointers?
I understand that the first line initializes a regular array of integers. However, the second line seems to be initializing a pointer or an array of pointers (I'm not sure).
Could someone explain:
What exactly is happening in the second line of code?
Why doesn't the second line compile as expected (or does it)?
When would we want to use a pointer initialization like this (if at all), compared to a regular array?
I'm trying to understand if there are specific scenarios where using the second approach would be preferable over the first.
You're conflating some concepts. As @ikegami noted, your second line:
int *numList = {1, 2, 3};
Gets treated as:
int *numList = 1;
Which not an array, nor a valid pointer. If you want to create an array of pointers, you use the same syntax as normal arrays, with the type being a pointer:
int* numList[] = {
&array[0],
&array[1],
&array[2]
};
Will create an array of 3 int pointers, pointing to your original array's elements.