【问题标题】:Why does the memory space show different value than the variable type occupies?为什么内存空间显示的值与变量类型占用的值不同?
【发布时间】: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


【解决方案1】:

edge 的类型为“pointer to struct Edge”(struct Edge *)——它存储了struct Edge 对象的地址。如果你得到16 的大小与struct Graph 一样大,这意味着你系统上的指针是4 字节宽。

大多数系统都有对齐要求,例如多字节对象从 2 或 4 的倍数(甚至更大的值)的地址开始。为了保持这些对齐限制,struct 类型可能在成员之间具有“填充”字节,因此 struct 的大小可能大于其成员大小的总和。

【讨论】:

    猜你喜欢
    • 2023-03-07
    • 2019-04-24
    • 1970-01-01
    • 1970-01-01
    • 2013-08-03
    • 1970-01-01
    • 2014-02-24
    • 1970-01-01
    • 2023-03-06
    相关资源
    最近更新 更多