的sizeof(结构)和sizeof(联合) [英] sizeof(struct) and sizeof(union)

查看:155
本文介绍了的sizeof(结构)和sizeof(联合)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

struct One{
       int x[6];
       short y[12];
} a;

union Two{
       int x[6];
       short y[12];
} b;

假定int为32位,而短裤是16位。

Assume that ints are 32 bits, and that shorts are 16 bits.

一个。是什么的sizeof(一)和sizeof(B)?

a. What is the sizeof(a) and sizeof(b)?

乙。如果&安培; A = 0x00320000 ,什么是&放大器; a.y

℃。如果和b = 0x00320400 ,什么是&放大器; b.y

可能有人请解释如何在联盟和结构的大小获得,以及如何得到的值的地址。据我所知,和放大器;一个和和b分别指的a和b的地址。但是,我不完全知道如何在什么&放得出; a.y和&安培; b.y将返回

Could someone please explain how to derive at the size of the union and struct, as well as how to get the values for the addresses. I understand that &a and &b mean the address of a and b respectively. However, i'm not exactly sure how to derive at what &a.y and &b.y will return.

推荐答案

虽然,在大多数情况下,答案是的实现定义的,为的的调试和故障排除程序员的需要知道的(可能)的答案是什么,他/她的平台:

Even though, for the most part, the answers are implementation-defined, a programmer for debugging and trouble-shooting needs to know what the (likely) answers are, on his/her platform:

一个。是什么的sizeof(一)和sizeof(B)?

a. What is the sizeof(a) and sizeof(b)?

sizeof的一个= 6 * 4 + 12 * 2 = 48,重要提示:如果您更改 12 13 ,这个计算很可能是错误的,因为填充通常会增加,大概2个字节,所以结构的大小会的的是的大小之和其元素。

sizeof a = 6 * 4 + 12 * 2 = 48. Important: if you change 12 to 13, this calculation would likely be wrong, as padding would typically be added, probably 2 bytes, and so the size of the struct would not be the sum of the sizes of its elements.

sizeof的B = MAX(6 * 4,12 * 2)= 24,因为在这个联盟, X 被覆盖。同样,如果你改变 12 13 ,有可能填充。

sizeof b = max(6 * 4, 12 * 2) = 24, because in this union, x and y are overlayed. Again if you change 12 to 13, there's likely padding.

乙。如果&安培; A = 0x00320000,什么是&放大器; a.y

b. if &a = 0x00320000, what is &a.y?

&安培; a.y = 0x00320000 + 6 * 4 = 0x00320018

&a.y = 0x00320000 + 6 * 4 = 0x00320018

℃。如果和b = 0x00320400,什么是与放大器; b.y

c. if &b = 0x00320400, what is &b.y?

&安培; b.y =和b(保证)

&b.y = &b (guaranteed)

这篇关于的sizeof(结构)和sizeof(联合)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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