首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

关于sizeof一个很奇怪有关问题

2012-02-21 
关于sizeof一个很奇怪问题#includestdio.h #includeiostream.h #includestring.h voidh(){}classA{p

关于sizeof一个很奇怪问题
#include   "stdio.h "
#include   "iostream.h "
#include   "string.h "
void   h()
{
}
class   A
{
private:
int   a;
char   b;
protected:
char   c;
public:
void   t()
{
cout < <sizeof(c) < <endl;
}
};
class   B
{
private:
int   a;
char   b;
int   c;
char   g[2];
public:
void   f()
{
cout < < "g[2]   : " < <sizeof(g) < <endl;
}
};
void   main()
{
char   *str= "012345678 ";
char   a[]= "0123456789 ";
char   a1[100]= "1234 ";
cout < <str < <endl;
cout < <sizeof(char) < <endl;//结果是1
cout < <sizeof(int) < <endl;//结果是4
cout < <sizeof(a) < <endl;//结果是11,因为计算到了 '\0 '
cout < <sizeof(a1) < <endl;//结果是100,因为最大容量是100
cout < <strlen(a1) < <endl;//结果是4,个函数内部实现是用一个循环计算到\0为止之前
//strlen()只能针对char   ,假如是int,就不行了,因为它是计算到\0为止的
       
cout < <sizeof(str) < < "       " < <sizeof(*str) < <endl;
//结果是4     指向字符串常量的字符指针?不是很懂
//字符常量是什么意思?   为什么不是1

char   a2[]= "a\0 ";
if(a2[2]== '\0 ')
{
cout < < "ni   hao   ! " < <endl;
cout < < "\\ " < < "0 " < <endl;
}
cout < < "a2   sizeof: " < <sizeof(a2) < <endl;//结果为三,\0是作为一个字符
       
A   a3;
//a3.t();
cout < < "class   A   sizeof   is " < <sizeof(A) < <endl;//是8
cout < < "Object   a   sizeof   is " < <sizeof(a) < <endl;//但是   a   的对象却是11
        B   b1;
//结果是16,为什么不是12呢?2个int加上3个char   不是只用12阿?
cout < < "class   B   sizeof   is: " < <sizeof(B) < <endl;

cout < < "Object   B   sizeof   is " < <sizeof(b1) < <endl;
b1.f();


int   b[5]={1,3};
int   *t;
t=b;
cout < <sizeof(b) < <endl;
cout < <sizeof(t) < <endl;

printf( "Hello! ");
}
/////


[解决办法]
======================================
cout < <sizeof(str) < < " " < <sizeof(*str) < <endl;
//结果是4 指向字符串常量的字符指针?不是很懂
//字符常量是什么意思? 为什么不是1
======================================
这里 "012345678 "就是字符常量,或者说字符串字面值
str本身是一个指针,占四个字节大小,里面的值为字符串 "012345678 "的地址

======================================================
A a3;
//a3.t();
cout < < "class A sizeof is " < <sizeof(A) < <endl;//是8
cout < < "Object a sizeof is " < <sizeof(a) < <endl;//但是 a 的对象却是11
======================================================
上次看了一个帖子,说结构和类按照8字节对齐取整,枚举按照4字节取整
A有一个int两个char,共6个字节,对齐为8字节。
char a[]= "0123456789 ";
这里a好像不是A的对象,而是字符串数组吧,加上 '\0 '刚好11

======================================================
B b1;
//结果是16,为什么不是12呢?2个int加上3个char 不是只用12阿?
cout < < "class B sizeof is: " < <sizeof(B) < <endl;


======================================================
12按8字节对齐,取16
[解决办法]
多换几个编译器先试试 。
另外,google “对齐”会给你后面几个打印的解释。
[解决办法]
看看字符串常量的数据类型是什么(是个常量字符数组)
看看内存字节对齐,这个并不属于语言语法范畴,属于编译技术
okokok
[解决办法]
求sizeof ,没有多大用,个人感觉
自己算就是了
由于编译器的不同
内存模式的不同(紧凑,松散)
类,结构等都各不相同

[解决办法]
B b1;
//结果是16,为什么不是12呢?2个int加上3个char 不是只用12阿?
cout < < "class B sizeof is: " < <sizeof(B) < <endl;

如果部对齐占用空间模型是 4 1 4 1 1共12字节,但是要对齐所以应为 4 3+1 4 1 1,考虑到B对象数组的问题,所以char g[2]应该填充,填充之后应该是 4 3+1 4 1+1 1+1共16字节

热点排行