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

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

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

问题

  1. /*
  2. * 注意:返回的数组必须使用malloc分配内存,假定调用者会使用free()释放内存。
  3. */
  4. int* spiralOrder(int** matrix, int matrixSize, int* matrixColSize, int* returnSize){
  5. *returnSize = matrixSize * matrixColSize[0];
  6. int *list = calloc(*returnSize, sizeof(int));
  7. return list;
  8. }
英文:

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.

  1. /*
  2. * Note: The returned array must be malloced, assume caller calls free().
  3. */
  4. int* spiralOrder(int** matrix, int matrixSize, int* matrixColSize, int* returnSize){
  5. *returnSize = matrixSize * matrixColSize[0];
  6. int list[] = calloc(0, (*returnSize)*sizeof(int));
  7. return list;
  8. }

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

  1. solution.c: In function spiralOrder
  2. Line 6: Char 18: error: invalid initializer [solution.c]
  3. int list[] = calloc(0, (*returnSize)*sizeof(int));
  4. ^~~~~~
  5. </details>
  6. # 答案1
  7. **得分**: 3
  8. 数组需要一个初始化列表来初始化它们。但在这种情况下,实际上你不需要一个数组,因为返回指向局部内存的指针将在函数返回后变为无效。
  9. 你想要将 `calloc` 的返回值赋给一个指针,然后返回该指针。另外,你调用 `calloc` 的方式是不正确的。第一个参数是元素的数量,第二个是每个元素的大小。
  10. ```c
  11. int *list = calloc(*returnSize, sizeof *list);
  12. 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.

  1. int *list = calloc(*returnSize, sizeof *list);
  2. 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:

确定