在C中的函数中动态分配数组

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

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

#include  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;kx = 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分都有值。

谢谢。

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

在那个函数中,你让arrayOfPoints指向一块内存,只带有指针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 

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

您不需要使用2个malloc。 请尝试以下代码。 您的方法尝试实际创建点矩阵并初始化每一行的第一个元素。

打印时,实际打印尚未完全初始化的第一行。

 int createAnArrayOfPoints(point** outArray,int* totalPoints) { // how many points? int neededPoints = howManyPoints(); // create an array of pointers *outArray =(point*)malloc(neededPoints * sizeof(point)); // fill the points with some data for testing for (int k=0;k 

您应该分配一个点结构数组,而不是指向点结构的指针数组。 此外,您正在混合间接级别。

使用局部变量point *array; 保持指向已分配数组的指针并将其作为array[i].x = k*10;...并将此指针存储为*outArray = array