用法:
sizeof + 变量名/ 类型。
返回结果是size_t(无符号整型), 以字节为单位的该类型内存大小。
如果是变量名, C内部根据变量名寻找其类型,然后根据类型去计算其大小。
特别注意:
C语言数组名同指针的区别。
sizeof(数组名): 返回的是数组的字节长度。
sizeof(指针); 返回的是4.
例子:
#include <iostream>
using namespace std;
typedef struct Test_Other_str
{ char i;
int j;
char h[55];
double k;
} Test_Other;
typedef struct Test_str
{
char cArr[22];
int i;
char cArr1[33];
double j;
struct {
char c1;
int intArr[4];
double dArr[6];
} inner_str;
char cArr2[44];
Test_Other* to;
} Test;
int main()
{
Test* test = (Test*)malloc(sizeof(Test));
Test_Other* test_other = (Test_Other*)malloc(sizeof(Test_Other));
test->to = test_other;
cout << sizeof(test->cArr) << endl;
cout << sizeof(test->cArr1) << endl;
cout << sizeof(test->cArr2) << endl;
cout << sizeof((test->to)->h) << endl;
free(test_other);
free(test);
system("pause");
}
C 会根据变量名正确找到类型, 然后根据类型计算其长度。 不用担心字节对齐或者他是不是嵌套结构体中。
这个实现的很奇妙哈, 不知道C++是怎么实现的。 后续有机会研究下吧。