Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在内部的双指针上使用malloc_C_Arrays_Pointers_Struct - Fatal编程技术网

在内部的双指针上使用malloc

在内部的双指针上使用malloc,c,arrays,pointers,struct,C,Arrays,Pointers,Struct,我有一个像这样编码的结构 typedef struct { double* xcoords; double* ycoords; char name[128]; int numOfCoords; } Image; 我使用Image*在堆上为32个映像的数组动态分配内存 Image* imgPointer; imgPointer = malloc(32 * sizeof(Image)); 我打算在图像中的double*xcoords和ycoords上使用mallo

我有一个像这样编码的结构

typedef struct {
    double* xcoords;
    double* ycoords;
    char name[128];
    int numOfCoords;
} Image;
我使用Image*在堆上为32个映像的数组动态分配内存

Image* imgPointer;
imgPointer = malloc(32 * sizeof(Image));
我打算在图像中的double*xcoords和ycoords上使用malloc来创建一个包含32个double的数组,但我很难弄清楚如何做到这一点

这样行吗?我是C新手,指针/结构的关系令人困惑

// Set up arrays and increment pointer to the next struct
imgPointer->xccords = malloc(32 * sizeof(double));
imgPointer->ycoords = malloc(32 * sizeof(double));
imgPointer++;
你有:

// Set up arrays and increment pointer to the next struct
imgPointer->xccords = malloc(32 * sizeof(double));
imgPointer->ycoords = malloc(32 * sizeof(double));
imgPointer++;
这将导致问题

问题1:您尚未为所有
图像的内部数据分配内存。您只为第一幅
图像的内部数据分配了内存

问题2:您已更改指针的值。它不指向由
malloc
返回的内存。对更改的指针值调用
free
,将导致未定义的行为。不调用
free
会导致内存泄漏

一个解决方案

// Allocate memory for the internal data of the Images
for ( int i = 0; i < 32; ++i )
{
   imgPointer[i].xccords = malloc(32 * sizeof(double));
   imgPointer[i].ycoords = malloc(32 * sizeof(double));
}
这样,就不需要使用
malloc
为它们分配内存,也不需要使用
free
来删除内存

您还可以创建一个
Image
s数组,因为您知道大小

Image images[32];

这样,就不需要使用
malloc
来创建
Image
s数组,也不需要
释放
分配的内存。

为什么
malloc(32*sizeof(double))
而不是
typedef结构{double xcoords[32];double ycoords[32];char name[128];int numOfCoords;}形象如果总是
32
…有效,但不
++
imgPointer
本身。相反,设置
Image*tmp=imgPointer
,然后执行
tmp->xcoords=
等等,最后是
tmp++
。这样,您就可以保留一个指向已分配的原始
imgPointer
数组的指针。实际上,我无法对32个元素进行硬编码。结构数组和结构内部的数组必须能够在满时通过调用realloc来保持增长。是的,它可以工作,但您的目标不明确,因此您可能会得到意外的结果。请在问题中包括您的目标。建议而不是
pointer=malloc(N*sizeof(*pointer_type)),使用
指针=malloc(sizeof*pointer*N)(sizeof变量与sizeof类型)更易于维护,错误代码的可能性更小。@colinspectily
将起作用,因为
图像[0]
不是指针,而是结构变量。
typedef struct {
    double xcoords[32];
    double ycoords[32];
    char name[128];
    int numOfCoords;
} Image;
Image images[32];