【发布时间】:2015-10-29 03:27:25
【问题描述】:
我有一个这样编码的结构...
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 个双精度数的数组,但我很难弄清楚如何去做。
这应该有效吗?我是 C 新手,指针/结构的关系令人困惑......
// Set up arrays and increment pointer to the next struct
imgPointer->xccords = malloc(32 * sizeof(double));
imgPointer->ycoords = malloc(32 * sizeof(double));
imgPointer++;
【问题讨论】:
-
为什么是
malloc(32 * sizeof(double))而不是typedef struct { double xcoords[32]; double ycoords[32]; char name[128]; int numOfCoords; } Image;如果总是32... -
这行得通,但不要
++imgPointer本身。相反,设置Image *tmp = imgPointer,然后设置tmp->xcoords = ...,以此类推,最后设置tmp++。这样,您将保留一个指向您已分配的原始imgPointer数组的指针。 -
我实际上无法对 32 个元素进行硬编码。 struct 数组和 struct 内部的数组必须能够通过在满时调用 realloc 来保持增长。
-
是的,它有效,但你的目标不明确,所以你可能会得到意想不到的结果。请在问题中包含您的目标。
-
推荐而不是
pointer = malloc(N * sizeof(*pointer_type));,使用pointer = malloc(sizeof *pointer * N);(sizeof 变量与sizeof 类型)更易于维护,代码出错的机会更少。