的sizeof() [英] sizeof()

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

问题描述

对于以下结构:


struct A {

int a;

double b;

char c;

};


struct A sa;

printf(" sizeof(A):% d \ n",sizeof(sa));


输出为

sizeof(A):16


为什么是16岁?


谢谢。


杰克

For the structure below:

struct A{
int a;
double b;
char c;
};

struct A sa;
printf("sizeof(A): %d\n", sizeof(sa));

The output is
sizeof(A): 16

Why it is 16?

Thanks.

Jack

推荐答案



Jack写道:

Jack wrote:

对于以下结构:


struct A {

int a;

double b;

char c;

};


struct A sa;

printf(" sizeof(A):%d \ n",sizeof(sa));


输出是

sizeof(A):16


为什么是16?
For the structure below:

struct A{
int a;
double b;
char c;
};

struct A sa;
printf("sizeof(A): %d\n", sizeof(sa));

The output is
sizeof(A): 16

Why it is 16?



为什么不呢?


Tom

why not?

Tom


Jack写道:
Jack wrote:

对于以下结构:


struct A {

int a ;

双b;

char c;

};


struct A sa;

printf(" sizeof(A):%d \ n",sizeof(sa));


输出为

sizeof(A):16


为什么是16?
For the structure below:

struct A{
int a;
double b;
char c;
};

struct A sa;
printf("sizeof(A): %d\n", sizeof(sa));

The output is
sizeof(A): 16

Why it is 16?



阅读常见问题解答,< http://c-faq.com/> ;,问题2.13。


Robert Gamble

Read the FAQ, <http://c-faq.com/>, question 2.13.

Robert Gamble


文章< 11 ********************* @ i3g2000cwc。 googlegroups.c om>,

Jack< ju ****** @ gmail.comwrote:
In article <11*********************@i3g2000cwc.googlegroups.c om>,
Jack <ju******@gmail.comwrote:

>对于结构下面:
>For the structure below:


> struct A {

int a;

double b;

char c;
};
>struct A{
int a;
double b;
char c;
};


struct A sa;

printf(" sizeof(A):%d \ n",sizeof( SA));
struct A sa;
printf("sizeof(A): %d\n", sizeof(sa));


>输出为
sizeof(A):16
>The output is
sizeof(A): 16


>为什么是16?
>Why it is 16?



该实现可能使用4个字节用于int,8个字节用于double,

1个字节用于char。但是实现需要填充结构,因此结构的大小是架构

对齐限制(通常是4个字节)的倍数,因此结构可能会得到

通过添加3个未使用的字节来填充。


如果结构没有填充,那么如果你有


struct一个sa2 [2];


然后sa2 [1]的地址在sa2 [0]

开始后将是13个字节,你会是要求系统从奇数字节

地址读取一个int。许多系统不能这样做,或者只能通过使用

特殊陷阱处理程序来实现,或者只能通过使用特殊的

load unaligned来实现。通常非常慢的说明。

-

法律 - 它是一种商品

- Andrew Ryan(The环球邮报,2005/11/26)

That implementation probably uses 4 bytes for int, 8 bytes for double,
1 byte for char. But implementations are required to pad structures so
that the size of the structure is a multiple of the architectural
alignment restrictions (often 4 bytes), so the structure likely gets
padded by adding 3 unused bytes.

If the structure were not padded, then if you had

struct A sa2[2];

then the address of sa2[1] would be 13 bytes after the start of sa2[0]
and you would be asking the system to read an int from an odd byte
address. A lot of systems cannot do that, or can only do that by using
special trap handlers, or can only do it by using special
"load unaligned" instructions that are often very slow.
--
"law -- it''s a commodity"
-- Andrew Ryan (The Globe and Mail, 2005/11/26)


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

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