Search code examples
arrayscpointersincompatibletypeerrorpointer-to-pointer

Incompatible pointer type pointer to array and double pointer to array


So i am new to programming and i have this program that i have to write, it has an array of integers and i have to pass it to a function with a pointer and then with a double pointer. After i wrote the code i had this error that i couldn't find a solution to. The error is :

initialization of 'int **' from incompatible pointer type 'int *' [-Wincompatible-pointer-type]

The code that i wrote is this:

int main(){
    int i;
    int arr[]={3,-15,19,0,-984};
    int *p=arr;
    funzione(p,sizeof(arr)/sizeof(arr[0]));      //The first function
    for(i=0;i<(sizeof(arr)/sizeof(arr[0]));i++)  //print of the single pointer (p)
        printf("%d\n",p[i]);
    int **g=p;                                   //the error results to be coming from p in this row
    for(i=0;i<(sizeof(arr)/sizeof(arr[0]));i++)  //print of the double pointer (g)
        printf("%d\n",g[i]);
    funzione2(g,sizeof(arr)/sizeof(arr[0]));     //The second function
    return 0;
}

My question is how can i remove this error.


Solution

  • The variable p has the type int * while the initialized variable g has the type int **.

    int **g=p;                                   //the error results to be 
    

    These pointer types are not compatible and there is no implicit conversion from one pointer type to another.

    You need to write

    int **g = &p;
    for(i=0;i<(sizeof(arr)/sizeof(arr[0]));i++)  //print of the double pointer (g)
        printf("%d\n",( *g )[i]);
    

    Pay attention to that the for loop can look the same way if you will declare the pointer g also the following way

    int ( *g )[5] = &arr;
    for(i=0;i<(sizeof(arr)/sizeof(arr[0]));i++)  //print of the double pointer (g)
        printf("%d\n",( *g )[i]);
    

    Also the expression sizeof(arr)/sizeof(arr[0]) has the unsigned integer type size_t. So it would be better to declare the variable i also as having the unsigned type size_t instead of the signed type int.

    size_t i;
    

    Though it is even much better to declare the variable i in the minimal scope where it is used as for example

    for( size_t i=0;i<(sizeof(arr)/sizeof(arr[0]));i++)  //print of the double pointer (g)
        printf("%d\n",( *g )[i]);
    

    And this called function

    funzione2(g,sizeof(arr)/sizeof(arr[0]));     //The first function
    

    is not the first function as it is written in the comment.:)