sizeof
的主要功能是什么(我是C++新手)。比如
int k=7;
char t='Z';
sizeof (k)
或 sizeof (int)
和 sizeof (char)
是什么意思?
最佳答案
sizeof(x)
返回变量或类型 x
占用的内存量(以字节为单位)。它与变量的值无关。
例如,如果您有一个任意类型的数组T
,那么该数组元素之间的距离就是sizeof(T)
。
int a[10];
assert(&(a[0]) + sizeof(int) == &(a[1]));
在变量上使用时,相当于在该变量的类型上使用:
T x;
assert(sizeof(T) == sizeof(x));
根据经验,最好尽可能使用变量名,以防类型发生变化:
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
仍然返回该类型的实例使用的内存量,但值得指出的是,这并不一定等于其成员的总和。
struct Foo { int a; char b; };
虽然 sizeof(int) + sizeof(char)
通常是 5
,但在许多机器上,sizeof(Foo)
可能是 >8
因为编译器需要pad out结构,使其位于 4 字节边界上。情况并非总是如此,您的机器上的 sizeof(Foo)
很可能是 5,但您不能依赖它。
关于c++ - sizeof 是做什么的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3203162/