这是在使用 C struct hack 时如何使用分配的“额外”内存?
问题:
我在下面有一个 C struct hack 实现。我的问题是如何使用通过 hack 分配的“额外”内存。有人可以给我一个使用额外内存的例子吗?
#include<stdio.h>
#include<stdlib.h>
int main()
{
struct mystruct {
int len;
char chararray[1];
};
struct mystruct *ptr = malloc(sizeof(struct mystruct) + 10 - 1);
ptr->len=10;
ptr->chararray[0] = 'a';
ptr->chararray[1] = 'b';
ptr->chararray[2] = 'c';
ptr->chararray[3] = 'd';
ptr->chararray[4] = 'e';
ptr->chararray[5] = 'f';
ptr->chararray[6] = 'g';
ptr->chararray[7] = 'h';
ptr->chararray[8] = 'i';
ptr->chararray[9] = 'j';
}
最佳答案
是的,这是(并且曾经是)C
中创建和处理可变大小的 struct
的标准方式。
这个例子有点冗长。大多数程序员会更巧妙地处理它:
struct mystruct {
int len;
char chararray[1]; // some compilers would allow [0] here
};
char *msg = "abcdefghi";
int n = strlen (msg);
struct mystruct *ptr = malloc(sizeof(struct mystruct) + n + 1);
ptr->len = n;
strcpy (ptr->chararray, msg);
}
关于工作中的 C struct hack,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16553542/