Search code examples
arrayscpointerssegmentation-faultpointer-to-pointer

Pointer Pointer leads to Segmentation Fault in C


Why can I create an array of pointers and dereference its (pointer-)elements.

int a = 1;
int* arr[1];

arr[0] = &a;

But cannot do the same with pointer to pointers:

int** arr2;
arr2[0] = &a;
--> Seg fault

Solution

  • from the first part

    int a = 1;
    int* arr[1];
    arr[0] = &a;
    

    So a is int. arr is what? It is int*[], an array of pointers to int. So the first and only element arr[0] is a pointer to an int and it is normal to assign an address of an int to it. The compiler is ok with that, since the operator & --- Address of --- assigns the address of the int a to a pointer to int, arr[0].

    from the second part

        int** arr2;
        arr2[0] = &a;
    

    arr2 is what? It is int**, a pointer to a pointer to int.

    • arr2 is int**
    • so *arr2 is int*, a pointer to an int
    • and **arr is an int

    arr2 is NOT what? NOT an array, so you can not write as you did arr[0].

    what you can write instead

    arr2 is int** so as in the first case it can get the address of a pointer to int. And you have an array of these here in the first part. So you for sure can write

        arr2 = &arr[0];
    

    Since & will extract the address of a pointer, and arr[0] is a pointer to int. And arr2 is int**, a pointer to a pointer to int.

    See the output

    toninho@DSK-2009:~/projects/um$ gcc -o tst -Wall -std=c17 pp.c
    toninho@DSK-2009:~/projects/um$ ./tst
    *arr[0] = 1 and **arr2 = 1
    toninho@DSK-2009:~/projects/um$ 
    

    of this code

    #include <stdio.h>
    
    int main()
    {
        int     a = 1;
        int*    arr[1]; // so arr is what? int*[]
    
        arr[0] = &a;
    
        int**   arr2; // arr2 is what? int**
        //arr2[0] = &a;
    
        arr2 = &arr[0];
    
        printf("*arr[0] = %d and **arr2 = %d\n",
            *arr[0], **arr2 );
        return 0;
    };