c - 如何通过函数获取数组并计算可变大小?

标签 c arrays

<分区>

我想使用 C 函数获取数组并计算可变大小 (@runtime)。我按如下方式实现此功能:

void getList(int **listArray, int *count){

  // get the total count
  int totalListCount = getTotalListCount();

  // Initialize the array
  int theList[totalListCount];
  memset( theList, 0, sizeof(int)*totalListCount );

  // Set the elements in the array
  for (int i = 0; i < totalListCount; i++) {
    theList[i] = theElementAtIndex(i);
  }

  // Assign the value to the pointer. 
  *count = totalListCount;
  *listArray = theList;
}

获取数组和计数后,我可以打印值:

int *list;
int count;

getList(&list, &count);

for (int i = 0; i < count; i++) {
    printf("list[%d]: %d \n", i, list[i]);
}

执行是否正确?我是否需要管理这些指针的内存,以及如何管理?

最佳答案

   // Initialize the array
   int theList[totalListCount];

你不应该返回函数的局部数组,你应该像这样使用 malloc:

   int *theList = malloc(totalListCount);

当然,不用的时候应该释放

关于c - 如何通过函数获取数组并计算可变大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20309933/

相关文章:

c - 为什么这个 'strncpy' 的实现有效?

使用 poll() 时正确处理 Ctrl-C

arrays - 未定义方法 `>' 对于 nil :NilClass in ruby array

c# - 如何将数组从 C# 代码隐藏显示到 ASPX 页面?

c - 在保持我的代码易于理解的同时格式化 scanf 时遇到问题

c++ - 嵌入式 Windows XP 中的网络接口(interface)设置

c - 打印一个 malloc() 声明的数组 - 打印越界的非常短的代码?

javascript - 如何将 JSON 对象转换为 Javascript 数组

arrays - Powershell阵列:何时使用它们;什么时候避免他们和使用它们的问题

c - 搜索函数返回错误的计数