1.首先看一个列子,在VC++6.0中用C语言进行写如下代码
会报错,
改成printf(“%d”,sizeof(stuct test));就可以
再用C++进行书写是可以的,
2.在C语言中是不能有空结构体的,在C++中是可以,大小视编辑器
而定,G++空结构大小为1
3.在C 语言中的用struct 在c++中用class 区别:
struct 成员默认public
class 成员默认private
4 在结构体嵌套时要小心,结构体的声明列如:
里面的结构体大小不算
5 注意公用体大小的计算特别之处
下面几道例子,如果没懂,看我博客.《内存对齐》
struct test
{
int a;
char b;
struct student
{
char c;
int d
};
};
5,结构体大小是重点,参照内存对齐
#include<stdio.h>
int main()
{
struct test
{
int a;
char b;
};
printf("%d",sizeof(test));
return 0;
}
Compiling...
ll.cpp
l.c
c:\users\liu\desktop\test1\lll\l.c(10) : error C2065: 'test' : undeclared identifier
执行 cl.exe 时出错.
lll.exe - 1 error(s), 0 warning(s)
#include<iostream>
int main()
{
struct test
{
int a;
char b;
};
printf("%d",sizeof(test));
return 0;
}
Compiling...
Skipping... (no relevant changes detected)
ll.cpp
ll.obj - 0 error(s), 0 warning(s)
#include<iostream>
using namespace std;
int main()
{
int *p = NULL;
cout <<"指针的大小"<<sizeof(p)<<endl;
cout<< "long 的大小"<<sizeof(long)<<endl;
struct test
{
short data1[2];
double b;
long g;
char a;
double data;
};
cout << sizeof(test) <<endl;
return 0;
}
指针的大小4
long 的大小4
32
Press any key to continue
#include<iostream>
using namespace std;
int main()
{
union
{
char name[10]; //10 +2 ----12
int data; //4 ----16
double count;//8
}sd;
cout<<"sd的大小"<<sizeof(sd)<<endl;
int *p = NULL;
cout <<"指针的大小"<<sizeof(p)<<endl;
cout<< "long 的大小"<<sizeof(long)<<endl;
struct test
{
short data1[2]; //4 +4
double b; //8 ---16
long g; //8 ---24
char a; //1
// ---25 + 7 ---32
union
{
char name[10]; //10 +2 ----12
int data; //4 ----16
double count;//8
}sd; // ---16
// -----38 +2
// --------40
};
cout << sizeof(test) <<endl;
return 0;
}
sd的大小16
指针的大小4
long 的大小4
40
Press any key to continue