【发布时间】:2021-08-25 08:55:23
【问题描述】:
#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 要求 4 字节两个整数=8byte+struct Edge *edge(4+4+4=12), 12+8=20 byte 但是 sizeof(struct Graph) 告诉我 16 为什么? *
【问题讨论】:
-
edge的类型为Edge*,所以它只存储一个地址。所以在你的系统上,地址要么是 8 字节长,要么是 4 字节,编译器会填充内存布局,使其对齐 -
谢谢,我明白了
-
您在表单中发布的代码问题应立即关闭。您不必费心为这个问题付出一些努力,但希望我们阅读此“代码”并为您提供帮助。 DV-ting 和近距离投票
-
首先,如果您在使用 C
struct时以字节为单位思考,那么您做错了。通常存在 alignment 可能会在结构成员之间创建“间隙”。也不要依赖sizeof(int)是 4 或sizeof(void *)是 8。
标签: c memory memory-management dynamic dynamic-memory-allocation