Search code examples
cpointersdynamic-allocation

Warning assignment from incompatible pointer type


So I was messing around with dynamic allocation to get a better understanding of it and I encountered the " warning assignment from incompatible pointer type " warning twice in my code, and i have no clue why.

Basically what i am trying to do is to dynamically allocate a queue of dynamically allocated 2-dimensional arrays.

First warning:

int * int_alloc_2d(unsigned int rows, unsigned int cols){
    int **array;
    int i;
    array = (int **)malloc(sizeof(int*)*rows);
    for(i=0;i<rows;i++)
        array[i]=(int*)malloc(sizeof(int)*cols);
    return array;
}

The first warning appears at the return array; line. This function is meant to dynamically allocate a 2-dimensional array

Second warning:

int main(int argc, char **argv){
    QUEUE *queue;
    queue = (QUEUE *)malloc(sizeof(QUEUE));
    int **a;
    a = int_alloc_2d(2,2);
    return 0;
}

The second warning appears at the a = int_alloc_2d(2,2); line. Here i am just allocating memory for the queue ( just 1 block ) and allocating a 2x2 2-dimensional array in the "a" variable.

What am I doing wrong?


Solution

  • You get the warning because the function is declared to return int* (one-asterisk pointer) but you are returning a pointer to pointer int**, a two-asterisk pointer.

    You can fix this by declaring the function return type as int**:

    int ** int_alloc_2d(unsigned int rows, unsigned int cols){
        int **array;
        int i;
        array = malloc(sizeof(int*)*rows);
        for(i=0;i<rows;i++)
            array[i]=malloc(sizeof(int)*cols);
        return array;
    }