c - 在 C 函数中动态分配数组

标签 c

我在编写的程序中遇到问题。这个小程序是一个简短的版本,只是为了展示问题。

对于这个例子,我定义了一个名为 point 的结构,它有一个 X 和 Y。我想要函数计算点的数量,在这个例子中我假设总是 5,但这在我的真实程序中不是常量.

#include <stdio.h>

typedef struct  point {
   int x;
   int y;
}point;


// suppose this is dynamic. it return a value according to some parameter;
int howManyPoints() {
   // for this demo assume 5.
   return 5;
}


int createAnArrayOfPoints(point** outArray,int* totalPoints) {

   // how many points?
   int neededPoints = howManyPoints();

   // create an array of pointers
   *outArray =malloc(neededPoints * sizeof(point*));

   // malloc memory of a point size for each pointer
   for (int i=0;i<neededPoints;i++) outArray[i] = malloc(sizeof(point));

   // fill the points with some data for testing
   for (int k=0;k<neededPoints;k++) {
      outArray[k]->x = k*10;
      outArray[k]->y = k*5;
   }

   // tell the caller the size of the array
   *totalPoints = neededPoints;

   return 1;
  }


int main(int argc, const char * argv[]) {

   printf("Program Started\n");

   point* arrayOfPoints;
   int totalPoints;
   createAnArrayOfPoints(&arrayOfPoints,&totalPoints);

   for (int j=0;j<totalPoints;j++) {
    printf("point #%d is at %d,%d\n",j,arrayOfPoints[j].x,arrayOfPoints[j].y);
   }

   printf("Program Ended\n");

   return 0;
}

我的控制台输出如下所示:

Program Started
point #0 is at 0,0
point #1 is at 0,0
point #2 is at 10,5
point #3 is at 0,0
point #4 is at 20,10
Program Ended

我做错了什么?我希望所有 5 点都具有值(value)..

谢谢。

最佳答案

您的数组表示不匹配: 在您的 main 中,您期望一组点 (point* arrayOfPoints;) 是一个连续的内存。但是,您在 createAnArrayOfPoints 中分配它的方式不同:

在该函数中,您让 arrayOfPoints 指向一 block 内存,该内存仅携带指向 point 的指针,并使用指向您分配的 point 大小的内存的指针对其进行初始化。这是一个太多的间接寻址,并且在打印时也会产生分配内存之外的访问。

相反,你应该这样做:

// Allocate enough memory to store an array of points of the expected size.
// To keep the code more readable, the resulting pointer is stored in a 
// intermediate variable.
points *theArray = malloc(neededPoints * sizeof(point));
if (theArray == NULL) {
    // do some error handling here as you apparently ran out of memory...
}

// fill the points with some data for testing
for (int k=0;k<neededPoints;k++) {
   theArray[k].x = k*10;
   theArray[k].y = k*5;
}

// Now save the pointer to the output-variable.
*outArray = theArray;

我还要添加一个警告:在使用返回值之前,您始终应该检查 malloc 是否成功。可能是您的内存不足,因此无法获得您请求的内容。

关于c - 在 C 函数中动态分配数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28657115/

相关文章:

c - 编写一个从 stdin 读取并打印到 stdout 的 C 程序,没有行长度的内置限制

c - float类型可以容纳的最大数字是多少?

c - 使用替代验证 key 的 fscanf()/vscanf() 函数系列的替代方案或如何创建自定义语言布局?

c - 指针失去其值+ execv 编译警告

c - 如何设置将用户输入拆分为多个部分并拆分那些较小部分的 C 函数?

c - linux下如何用mingw使用splint

c++ - 如何同时等待 I/O 完成端口和事件?

c - malloc 和 calloc

c - 使用 fopen_s 将文件保存在 "Program Files/myApplication"文件夹中

c - 输入末尾的预期声明或语句 - 错误