您的位置:首页 > 其它

基础备忘:结构体、指针所占的内存大小

2012-08-26 22:00 344 查看
结构体按最长的数据类型对齐,所占内存的大小为结构体的所占内存最大的成员数据类型的整数倍。而各种数据类型的指针,所占的内存是4字节。示例如下:

#include<iostream>
using namespace std;
typedef struct t
{
bool a;
int b;
bool c;
struct t*next;
};
struct t1
{
bool a;
short b;
bool c;
};
struct t2
{
bool a;
char b;
bool c;
};
int main()
{
cout << "sizeof(t) "<<sizeof(t) << endl <<"sizeof(t1) "<< sizeof(t1) << endl <<"sizeof(t2) "<< sizeof(t2) << endl;
cout<<"int "<<sizeof(int)<<endl<<"bool "<<sizeof(bool)<<endl<<"short "<<sizeof(short)<<endl<<"char "<<sizeof(char)<<endl;
struct t *tttt;
cout<<"tttt "<<sizeof(tttt)<<endl;

char **a[3][4];
cout<<"sizeof(a) "<<sizeof((a))<<" sizeof(&a)"<<sizeof (&a)<<endl;//&a大小是4
double *p;
cout<<"sizeof(*double) "<<sizeof(p)<<endl;//大小是4
int *q;
cout<<"sizeof(*int) "<<sizeof(q)<<endl; //大小是4
char *s;
cout<<"sizeof(*char) "<<sizeof(s)<<endl;
char b[10];
cout<<"sizeof(b) "<<sizeof(b)<<endl;
char *c[10];
cout<<"sizeof(c) "<<sizeof(c)<<" sizeof(*c) "<<sizeof(*c)<<" sizeof(&c) "<<sizeof(&c)<<endl;
int x;
int *r=&x;
int **rr=&r;
cout<<"sizeof(rr) "<<sizeof(rr)<<endl;//大小是4 ,rr是二级指针,是指向指针的指针,本质是还是指针。
system("pause");
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  struct c system