Cpp代码
1.// Example of the sizeof keyword
2.size_t i = sizeof( int );
3.
4.struct align_depends {
5. char c;
6. int i;
7.};
8.size_t size = sizeof(align_depends); // The value of size depends on
9. // the value set with /Zp or
10. // #pragma pack
11.
12.int array[] = { 1, 2, 3, 4, 5 }; // sizeof( array ) is 20
13. // sizeof( array[0] ) is 4
14.size_t sizearr = // Count of items in array
15. sizeof( array ) / sizeof( array[0] );
// Example of the sizeof keyword
size_t i = sizeof( int );
struct align_depends {
char c;
int i;
};
size_t size = sizeof(align_depends); // The value of size depends on
// the value set with /Zp or
// #pragma pack
int array[] = { 1, 2, 3, 4, 5 }; // sizeof( array ) is 20
// sizeof( array[0] ) is 4
size_t sizearr = // Count of items in array
sizeof( array ) / sizeof( array[0] );
1. 用法
1.1 sizeof和new、delete等一样,是关键字,不是函数或者宏。
1.2 sizeof返回内存中分配的字节数,它和操作系统的位数有关。例如在常见的32位系统中,int类型占4个字节;但是在16位系统中,int类型占2个字节。
1.3 sizeof的参数可以是类型,也可以是变量,还可以是常量。对于相同类型,以上3中形式参数的sizeof返回值相同。
Cpp代码
1.int a;
2.sizeof(a); // = 4
3.sizeof(int); // = 4
4.sizeof(1); // = 4
int a;
sizeof(a); // = 4
sizeof(int); // = 4
sizeof(1); // = 4
1.4 C99标准规定,函数、不能确定类型的表达式以及位域(bit-field)成员不能被计算s
izeof值,即下面这些写法都是错误的。
Cpp代码
1.void fn() { }
2.sizeof(fn); // error:函数
3.sizeof(fn()); // error:不能确定类型
4.struct S
5.{
6. int a : 3;
7.};
8.S sa;
9.sizeof( sa.a ); // error:位域成员
void fn() { }
sizeof(fn); // error:函数
sizeof(fn()); // error:不能确定类型
struct S
{
int a : 3;
};
S sa;
sizeof( sa.a ); // error:位域成员
1.5 sizeof在编译阶段处理。由于sizeof不能被编译成机器码,所以sizeof的参数不能被编译,而是被替换成类型。
Cpp代码
1.int a = -1;
2.sizeof(a=3); // = sizeof(a) = sizeof(int) = 4
3.cout<
C语言内存分配示例 与 字节对齐示例
最新推荐文章于 2024-08-22 13:44:05 发布