在内部的双指针上使用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];