cmalloccalloc

How am I supposed to initialize a array using calloc inside a function?


While trying to solve a problem called spiral matrix, I encountered a problem that i was not able to initialize a array inside of a function using calloc.

/*
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* spiralOrder(int** matrix, int matrixSize, int* matrixColSize, int* returnSize){
    *returnSize = matrixSize * matrixColSize[0];
    int list[] = calloc(0, (*returnSize)*sizeof(int));
    return list;

}

While trying to compile I am getting this exception Can someone explain why is this happening

solution.c: In function ‘spiralOrder’
Line 6: Char 18: error: invalid initializer [solution.c]
     int list[] = calloc(0, (*returnSize)*sizeof(int));
                  ^~~~~~

Solution

  • Arrays require an initializer list to initialize them. But you don't actually want an array in this case, as returning a pointer to local memory will be invalid once the function returns.

    You want to assign the return value of calloc to a pointer and return that pointer. Also, you're calling calloc incorrectly. The first parameter is the number of elements and the second is the size of each element.

    int *list = calloc(*returnSize, sizeof *list);
    return list;