为什么内存 space 显示的值与变量类型占用的值不同?
Why does the memory space show different value than the variable type occupies?
#include <stdlib.h>
#include <stdio.h>
struct Edge
{
// for every edge u,v,w
int u;
int v;
int w;
};
struct Graph
{
// for graph vertex v edge e
int V;
int E;
struct Edge *edge;
};
int main()
{
int i,j,k,w,s;
// open memory for graph g
struct Graph *g = (struct Graph*)malloc(sizeof(struct Graph));
//expected 20 but it show me 16
printf("%d",sizeof(struct Graph));
return 0;
}
*int requirement 4 byte two integer=8byte+struct Edge *edge(4+4+4=12), 12+8=20 byte 但是 sizeof(struct Graph) 告诉我 16 为什么? *
edge
的类型为“指向 struct Edge
的指针”(struct Edge *
)——它存储了 struct Edge
的地址目的。如果你得到 16
的大小为 struct Graph
,这意味着你的系统上的指针是 4 个字节宽。
大多数系统都有对齐要求,因此多字节对象的起始地址是 2 或 4 的倍数(甚至更大的值)。为了保持这些对齐限制,struct
类型可能在成员之间有“填充”字节,因此 struct
的大小可能大于其成员大小的总和。
#include <stdlib.h>
#include <stdio.h>
struct Edge
{
// for every edge u,v,w
int u;
int v;
int w;
};
struct Graph
{
// for graph vertex v edge e
int V;
int E;
struct Edge *edge;
};
int main()
{
int i,j,k,w,s;
// open memory for graph g
struct Graph *g = (struct Graph*)malloc(sizeof(struct Graph));
//expected 20 but it show me 16
printf("%d",sizeof(struct Graph));
return 0;
}
*int requirement 4 byte two integer=8byte+struct Edge *edge(4+4+4=12), 12+8=20 byte 但是 sizeof(struct Graph) 告诉我 16 为什么? *
edge
的类型为“指向 struct Edge
的指针”(struct Edge *
)——它存储了 struct Edge
的地址目的。如果你得到 16
的大小为 struct Graph
,这意味着你的系统上的指针是 4 个字节宽。
大多数系统都有对齐要求,因此多字节对象的起始地址是 2 或 4 的倍数(甚至更大的值)。为了保持这些对齐限制,struct
类型可能在成员之间有“填充”字节,因此 struct
的大小可能大于其成员大小的总和。