原文: http://blog.163.com/[email protected]/blog/static/1669557492011825111853370/
一直都認為C++學的可以,現在才發現被鄙視了,一些非常基礎的知識搞不清楚。
sizeof一些小解。
一:
#include <iostream>
using namespace std ;
class A
{
public :
int a ;
static int b ;
A() ;
~A() ;
}; //sizeof = 4 很簡單。
class B
{
public :
int a ;
char b ;
B() ;
~B() ;
}; //sizeof = 8 記憶體對齊,資料對齊
class C
{
public :
float a ;
char b ;
C() ;
~C() ;
}; //sizeof = 8 記憶體對齊,資料對齊
class D
{
public :
float a ;
int b ;
char c ;
D() ;
~D() ;
}; //sizeof = 12 記憶體對齊,資料對齊
class E
{
public :
double a ;
float b ;
int c ;
char d ;
E() ;
~E() ;
};
int main()
{
cout << sizeof( A ) << endl ;
cout << sizeof( B ) << endl ;
cout << sizeof( C ) << endl ;
cout << sizeof( D ) << endl ;
cout << sizeof( E ) << endl ;
return 0 ;
}
二:
#include <iostream>
using namespace std ;
void fun( char ch[] )
{
cout << sizeof( ch ) << endl ;
}
int main()
{
char ch[] = "adsasd" ;
fun( ch ) ;
return 0 ;
}
先了解下面這個事:
void fun( char ch[] )
Void fun( char* ch )
Void fun( char ch[10] )
上面三條語句都是相等的,上面的ch都會轉換指針,在fun函數中ch是指針而不是數組的第一個元素的位址。
是以上面三條語句,無論那條cout << sizeof( ch ) << endl ; 都會得到 4 , Int(指針) 的大小。