我刚刚了解到,在使用 malloc 函数时,可以增加分配给结构的内存大小。例如,你可以有一个这样的结构:
struct test{
char a;
int v[1];
char b;
};
这显然只有 2 个字符和 1 个 int 的空间(实际上是指向 int 的指针,但无论如何)。但是您可以调用 malloc 以使结构包含 2 个字符和任意数量的整数(假设为 10):
int main(){
struct test *ptr;
ptr = malloc (sizeof(struct test)+sizeof(int)*9);
ptr->v[9]=50;
printf("%d\n",ptr->v[9]);
return 0;
}
此处的输出将是“50”打印在屏幕上,这意味着结构内的数组最多可容纳 10 个整数。
我对经验丰富的 C 程序员的问题:
最佳答案
...Which clearly has space for only 2 chars and 1 int (pointer to an int in reality, but anyway)...
已经不对了。数组不是指针。您的结构可容纳 2
char
的空间s 和 1 int
.那里没有任何类型的指针。您声明的内容本质上等同于struct test {
char a;
int v;
char b;
};
1 个元素的数组和普通变量之间没有太大区别(只有概念上的区别,即语法糖)。
...But you could call malloc in such a way to make it hold 1 char and as many ints as you wanted (let's say 10)...
呃...如果你想让它保持 1
char
, 你为什么用 2 char
声明你的结构吗???无论如何,为了实现一个灵活大小的数组作为结构的成员,您必须将数组放在结构的最末端。
struct test {
char a;
char b;
int v[1];
};
然后你可以为你的结构分配内存,最后为数组分配一些“额外”内存
struct test *ptr = malloc(offsetof(struct test, v) + sizeof(int) * 10);
(注意
offsetof
是如何用于计算正确大小的)。这样它就可以工作,给你一个大小为 10 和 2 的数组
char
s 在结构中(如声明的那样)。它被称为“struct hack”,它主要取决于数组是结构的最后一个成员。C99 版本的 C 语言引入了对“struct hack”的专门支持。在 C99 中,它可以作为
struct test {
char a;
char b;
int v[];
};
...
struct test *ptr = malloc(sizeof(struct test) + sizeof(int) * 10);
What is happening behind the scenes here? Does the computer allocate 2+4 (2 chars + pointer to int) bytes for the standard "struct test", and then 4*9 more bytes of memory and let the pointer "ptr" put whatever kind of data it wants on those extra bytes?
malloc
分配与您要求分配的内存一样多的内存。它只是一个单一的原始内存块。没有其他事情发生在“幕后”。您的结构中没有任何类型的“指向 int 的指针”,因此任何涉及“指向 int 的指针”的问题都毫无意义。Does this trick only works when there is an array inside the struct?
好吧,这就是重点:访问额外的内存,就好像它属于声明为结构的最后一个成员的数组一样。
If the array is not the last member of the struct, how does the computer manage the memory block allocated?
它什么都管不了。如果数组不是结构的最后一个成员,那么尝试使用数组的额外元素将丢弃在数组之后声明的结构成员。这是非常没用的,这就是为什么“灵活”数组必须是最后一个成员的原因。
关于c - 通过 Malloc 增加分配给结构的内存大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7436098/