Possible Duplicate:
Why isn’t sizeof for a struct equal to the sum of sizeof of each member?
我不明白为什么会这样:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
char b;
int a;
} A;
typedef struct
{
char b;
} B;
int main() {
A object;
printf("sizeof char is: %d\n",sizeof(char));
printf("sizeof int is: %d\n",sizeof(int));
printf("==> the sizeof both are: %d\n",sizeof(int)+sizeof(char));
printf("and yet the sizeof struct A is: %d\n",sizeof(object));
printf("why?\n");
B secondObject;
printf("pay attention that the sizeof struct B is: %d which is equal to the "
"sizeof char\n",sizeof(secondObject));
return 0;
}
我想我已经在代码中解释了我的问题,没有必要再解释了。除此之外我还有一个问题: 我知道在:堆/静态堆/堆栈上有分配,但这意味着分配位置未知,怎么可能?
我正在谈论这个例子:
typedef struct
{
char *_name;
int _id;
} Entry;
int main()
{
Entry ** vec = (Entry**) malloc(sizeof(Entry*)*2);
vec[0] = (Entry *) malloc(sizeof (Entry));
vec[0]->_name = (char*)malloc(6);
strcpy (vec[0]->_name, "name");
vec[0]->_id = 0;
return 0;
}
我知道: vec 在堆栈上。 *vec 在堆上。 *vec[0] 在堆上。 vec[0]->id 在堆上。
但是: vec[0]->_name 未知 为什么?
最佳答案
结构成员之间和结构末尾有未指定的填充量。在 C 中,结构对象的大小大于或等于其成员大小的总和。
关于c - 副作用的大小和分配位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14662312/