sizeof是什么? [英] What does sizeof do?

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

问题描述

sizeof (我是C ++新手)的主要功能是什么。例如

What is the main function of sizeof (I am new to C++). For instance

int k=7;
char t='Z';

什么 sizeof(k) code> sizeof(int)和 sizeof(char)是什么意思?

What do sizeof (k) or sizeof (int) and sizeof (char) mean?

推荐答案

sizeof(x) 返回变量或 x 占用的内存量(以字节为单位)。

sizeof(x) returns the amount of memory (in bytes) that the variable or type x occupies. It has nothing to do with the value of the variable.

例如,如果你有一个任意类型的数组 T 那么数组元素之间的距离就是 sizeof(T)

For example, if you have an array of some arbitrary type T then the distance between elements of that array is exactly sizeof(T).

int a[10];
assert(&(a[0]) + sizeof(int) == &(a[1]));

在变量上使用时,它等同于对该变量的类型使用它:

When used on a variable, it is equivalent to using it on the type of that variable:

T x;
assert(sizeof(T) == sizeof(x));

根据经验,最好尽可能使用变量名case类型更改:

As a rule-of-thumb, it is best to use the variable name where possible, just in case the type changes:

int x;
std::cout << "x uses " << sizeof(x) << " bytes." << std::endl
// If x is changed to a char, then the statement doesn't need to be changed.
// If we used sizeof(int) instead, we would need to change 2 lines of code
// instead of one.

当用于用户定义的类型时, sizeof 仍然返回该类型的实例使用的内存量,但值得指出的是,这不必等于其成员的总和。

When used on user-defined types, sizeof still returns the amount of memory used by instances of that type, but it's worth pointing out that this does not necessary equal the sum of its members.

struct Foo { int a; char b; };

sizeof(int)+ sizeof(char)通常 5 ,在许多机器上, sizeof(Foo)可以 / code>,因为编译器需要填充结构,使其位于4字节边界。这并不总是这样,很可能在你的机器上 sizeof(Foo)将是5,但你不能依赖它。

While sizeof(int) + sizeof(char) is typically 5, on many machines, sizeof(Foo) may be 8 because the compiler needs to pad out the structure so that it lies on 4 byte boundaries. This is not always the case, and it's quite possible that on your machine sizeof(Foo) will be 5, but you can't depend on it.

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

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