英文:
How am I supposed to initialize a array using calloc inside a function?
问题
/*
* 注意:返回的数组必须使用malloc分配内存,假定调用者会使用free()释放内存。
*/
int* spiralOrder(int** matrix, int matrixSize, int* matrixColSize, int* returnSize){
*returnSize = matrixSize * matrixColSize[0];
int *list = calloc(*returnSize, sizeof(int));
return list;
}
英文:
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));
^~~~~~
</details>
# 答案1
**得分**: 3
数组需要一个初始化列表来初始化它们。但在这种情况下,实际上你不需要一个数组,因为返回指向局部内存的指针将在函数返回后变为无效。
你想要将 `calloc` 的返回值赋给一个指针,然后返回该指针。另外,你调用 `calloc` 的方式是不正确的。第一个参数是元素的数量,第二个是每个元素的大小。
```c
int *list = calloc(*returnSize, sizeof *list);
return list;
英文:
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;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论