如何在函数内部使用calloc初始化数组?

huangapple go评论104阅读模式
英文:

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;

huangapple
  • 本文由 发表于 2023年8月10日 22:24:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76876661.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定