小编re.*_*.m7的帖子

为什么在通过引用传递时C中结构的大小增加

我一直在尝试理解结构以及它们的大小如何根据声明成员的顺序以及填充和对齐与之关联的方式而有所不同.

当我声明结构类似于你在下面看到的结构时,我得到了我期望的内存大小,即4个字节.

typedef struct {
    int x;
} GPS;

int main()
{
   GPS st;
   st.x = 42;
   int size;
   size = sizeof(st);
   printf("\n Size: %d", size);
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是当我通过引用函数传递结构时,结构将其大小增加到8个字节,我不知道为什么.我阅读了有关位对齐和填充的所有内容,但似乎没有任何大小增加的内容.

typedef struct {
    int x;
} GPS;

int main()
{
   GPS st;
   st.x = 42;
   printStruct(&st);
   return 0;
}

void printStruct(GPS *stptr)
{
    int size;
    char *ch = (char *)stptr;
    size = sizeof(stptr);
    printf("Size: %i \n", size);
}
Run Code Online (Sandbox Code Playgroud)

所以我的问题是,为什么结构在通过引用传递时会增加?

c struct

0
推荐指数
1
解决办法
74
查看次数

标签 统计

c ×1

struct ×1