sizeof() 函数如何用于 C 中的结构? [英] How the sizeof() function works for Structures in C?

查看:24
本文介绍了sizeof() 函数如何用于 C 中的结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

结构定义如下

typedef struct Sample
{
  int test;
  char strtest;
} Sample;

在 Main Function 中,我调用了 Sizeof 结构.

In Main Function, I called Sizeof the structure.

sizeof(struct Sample)

我听说结构上 sizeof 的返回值可能不正确.如果是这种情况,我应该怎么做才能获得正确的值?

I've heard the return value of sizeof on structures could be incorrect. If this is the case, what should I do to get the right value?

推荐答案

它确实返回了一个可靠的值 - 只是并不总是您期望的值.

It does return a reliable value - just not always the value you expect.

在示例结构中,您假设一个 1 字节的字符和 4 字节的 int,但您没有得到 "5" 的结果.

In Sample structure, you are assuming a 1 byte char and 4 byte int, but you do not get a result of "5" .

因为结构被填充,所以元素从它们的自然边界开始.你更有可能得到8"的结果.

Because the structure is padded so that elements start on their natural boundaries. you are more likely to get a result of "8".

Wiki 很好地解释了这一点:http://en.wikipedia.org/wiki/Sizeof - 在结构Padding",靠近底部.

Wiki explains this pretty well: http://en.wikipedia.org/wiki/Sizeof - at "Structure Padding", near the bottom.

这篇关于sizeof() 函数如何用于 C 中的结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆