这是如何使用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';
}
Run Code Online (Sandbox Code Playgroud)
wal*_*lyk 16
是的,这是(并且是)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);
}
Run Code Online (Sandbox Code Playgroud)
自从我读到这篇文章(http://blogs.msdn.com/b/oldnewthing/archive/2004/08/26/220873.aspx)以来,我一直喜欢使用struct hack:
#include<stdio.h>
#include<stdlib.h>
int main()
{
struct mystruct {
int len;
char chararray[1];
};
int number_of_elements = 10;
struct mystruct *ptr = malloc(offsetof(struct mystruct, chararray[number_of_elements]));
ptr->len = number_of_elements;
for (i = 0; i < number_of_elements; ++i) {
ptr->chararray[i] = 'a' + i;
}
}
Run Code Online (Sandbox Code Playgroud)
我发现不必记住1是否需要减去(或添加或其他)是好的.这也有0在数组定义中使用的情况下工作的好处,并非所有编译器都支持,但有些支持.如果分配基于offsetof()您,则无需担心可能的细节会使您的数学错误.
它的工作原理没有变化,struct是C99灵活的数组成员.