如何使用 malloc 更改结构的大小
How to change the size of a struct using malloc
我正在制作一个未定义大小的结构。
#define namemax 128
struct Image{
char name[namemax+1];
int length;
double *array; //double array[256]
};
struct Image* graph;
graph=malloc(max*sizeof(struct Image));
如果我定义 array[256]
,一切正常。
但是如果我使用 double *array
,然后写
graph[check].array = malloc( 100 * sizeof(double *));
它创建了一个段错误。
我想知道如何使用 malloc
和 realloc
为数组定义大小。
如果我在数组中添加值,它会显示段错误。
struct Image* graph;//outside the while loop
while: //it is inside the while loop
//basically it read different name each line, and put the x and y to the array
graph[check].array = malloc( 100 * sizeof(double));
check++;
strcpy( graph[check].name,type);
graph[check].array[count]=shiftX;
graph[check].array[count+1]=shiftY;
那是因为 double * array
正在声明一个指向数组的指针,而不是存储。你想在这里声明存储。最简单的方法是简单地将数组定义为 double array[1]
并确保它是结构中的最后一个元素。然后,您可以使用 malloc() 和 realloc() 为结构分配 space,方法是将基本结构的大小加上数组的大小(sizeof double * 数组元素的数量)。
我看到的一个问题是使用 sizeof(double *) 而不是 sizeof(double),即使如果您使用的是 x86-64 架构,两者是相同的。
我认为它会导致段错误,因为在 malloc 中你已经说过 sizeof(double *)
(实际上你声明了一个数组的数组)。
试着说 sizeof(double)
它可能会起作用,但我不确定,因为我还没有测试过它。
顺便说一句,当你静态声明数组时,你在声明你的结构变量时为它保留 space 但当你将它声明为指针(动态数组)时,你应该为它保留 space您可以更改数组的大小。你应该用realloc
google吧
我正在制作一个未定义大小的结构。
#define namemax 128
struct Image{
char name[namemax+1];
int length;
double *array; //double array[256]
};
struct Image* graph;
graph=malloc(max*sizeof(struct Image));
如果我定义 array[256]
,一切正常。
但是如果我使用 double *array
,然后写
graph[check].array = malloc( 100 * sizeof(double *));
它创建了一个段错误。
我想知道如何使用 malloc
和 realloc
为数组定义大小。
如果我在数组中添加值,它会显示段错误。
struct Image* graph;//outside the while loop
while: //it is inside the while loop
//basically it read different name each line, and put the x and y to the array
graph[check].array = malloc( 100 * sizeof(double));
check++;
strcpy( graph[check].name,type);
graph[check].array[count]=shiftX;
graph[check].array[count+1]=shiftY;
那是因为 double * array
正在声明一个指向数组的指针,而不是存储。你想在这里声明存储。最简单的方法是简单地将数组定义为 double array[1]
并确保它是结构中的最后一个元素。然后,您可以使用 malloc() 和 realloc() 为结构分配 space,方法是将基本结构的大小加上数组的大小(sizeof double * 数组元素的数量)。
我看到的一个问题是使用 sizeof(double *) 而不是 sizeof(double),即使如果您使用的是 x86-64 架构,两者是相同的。
我认为它会导致段错误,因为在 malloc 中你已经说过 sizeof(double *)
(实际上你声明了一个数组的数组)。
试着说 sizeof(double)
它可能会起作用,但我不确定,因为我还没有测试过它。
顺便说一句,当你静态声明数组时,你在声明你的结构变量时为它保留 space 但当你将它声明为指针(动态数组)时,你应该为它保留 space您可以更改数组的大小。你应该用realloc
google吧