I have come across an array with only one element. This array is defined inside a structure. Which goes like this:
我遇到了一个只有一个元素的数组。该数组在结构内定义。这是这样的:
typedef struct abc
{
int variable1;
char variable2;
float array[1];
};
I don't understand why this array is required, why can't we define just a variable or define a pointer(considering array property).
我不明白为什么这个数组是必需的,为什么我们不能只定义一个变量或定义一个指针(考虑数组属性)。
I want to use it. How do i use this variable? abc.array[0]
seems correct. Isn't it.
我想用它。我如何使用这个变量? abc.array [0]似乎是正确的。不是吗
Addition I am not using any dynamic memory allocation then what is its significance ?
另外我没有使用任何动态内存分配那么它的意义是什么?
1 个解决方案
#1
2
It's probably what is called the "struct hack". By allocating a large block of memory, the array becomes dynamic. The one element is just a placeholder to make it compile, in fact there will be many floats.
它可能就是所谓的“结构黑客”。通过分配大块内存,该阵列变得动态。一个元素只是一个占位符来进行编译,实际上会有很多浮点数。
The dynamic array has to be the last element.
动态数组必须是最后一个元素。
Use like this:
使用这样:
struct abc *ptr = malloc(sizeof(struct abc) + (N-1) * sizeof(float));
ptr->variable1 = N; /* usually store length somewhere in struct*/
#1
2
It's probably what is called the "struct hack". By allocating a large block of memory, the array becomes dynamic. The one element is just a placeholder to make it compile, in fact there will be many floats.
它可能就是所谓的“结构黑客”。通过分配大块内存,该阵列变得动态。一个元素只是一个占位符来进行编译,实际上会有很多浮点数。
The dynamic array has to be the last element.
动态数组必须是最后一个元素。
Use like this:
使用这样:
struct abc *ptr = malloc(sizeof(struct abc) + (N-1) * sizeof(float));
ptr->variable1 = N; /* usually store length somewhere in struct*/