arrayscpointers

What is the difference between a regular array, and array of pointers


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:

  1. What exactly is happening in the second line of code?

  2. Why doesn't the second line compile as expected (or does it)?

  3. 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.


Solution

  • 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.