先貼上一份完整的代碼:
#include <stdio.h>
#include <string.h>
void func(char str[50])
{
printf("A %d B %d ",sizeof(str), strlen(str));
}
int main(void)
{
char stra[] = "HelloWorld";
char *strb = stra;
printf("C %d D %d ",sizeof(stra), sizeof(strb++));
func(++strb);
printf("E %d F %d\n",strlen(stra), strlen(strb++));
return 0;
}
/*
C = 11,計算包括'\0'
D = 4, 指針
A = 4, 儘管形參是數組,但傳遞的依然是指針
B = 9, 因爲++strb, 使得strb = "elloWorld".
E = 10, '\0'之前的所有字符
F = 9, 同上分析。
*/
注意:sizeof(“數組名”)的時候 會自動添加上’\0’所以位數+1;
注意:strlen(“數組名”) 確切的數就是看裏面實際添加了多少個有效數值;
注意:char name[2]=”ab”;可以嗎?
注意:char str[20]=”0123456789”;
int a=strlen(str); //a=10;
int b=sizeof(str); //而b=20; 而不是10!!
char str2[5] = {'H','e','l','l','o'};
printf("G %d H %d\n",sizeof(str2), strlen(str2)); //strlen 出錯 因爲沒有'\0'
char str1[] = “Hello”;
sizeof (str1 ) = 6 (自動加了'\0')
strlen (str1 ) = 5 (字符串的長度)
//strlen:計算長度,到’\0’爲止
//sizeof:計算字符數組大小(包括’\0’)
char *p1 = "Hello";
sizeof ( p1 ) = 4 (p1是一個指針,大小爲4)
char *p2[]={"hello","world"};
sizeof ( p2 ) = 8 (p2是長度爲2的字符串數組)
int n = 10;
int *q = &n;
sizeof ( n ) = 4 (整型大小爲4)
sizeof ( q ) = 4 (q是一個指針,大小爲4)
2.動態分配內存
int *p = (int *)malloc( 100 );
sizeof ( p ) = 4 (p是一個指針,大小爲4)
3.函數參數
void Function1( char p[],int num ){
sizeof ( p ) = 4 (數組在作爲函數參數時均化爲指針)
}
void Function2( int p[],int num ){
sizeof ( p ) = 4 (數組在作爲函數參數時均化爲指針)
}
// 數組作爲參數傳遞時均作爲指針傳遞,所以sizeof=4
多重繼承
class A{};
class B{};
class C : public A, public B{};
class D : virtual public A{};
class E : virtual public A, virtual public B{};
//sizeof(A) = 1,sizeof(B) = 1 (空類大小爲1,編譯器安插一個char給空類,用來標記它的每一個對象)
//sizeof ( C ) = 1 (繼承或多重繼承後空類大小還是1)
//sizeof(D) = 4 (虛繼承時編譯器爲該類安插一個指向父類的指針,指針大小爲4)
//sizeof(E) = 8 (指向父類A的指針與父類B的指針,加起來大小爲8)
sizeof(A) = 1 sizeof(B) = 1 sizeof ( C ) =1 sizeof(D) =4 sizeof(E) = 8
5.數據對齊
類(或結構)的大小必需爲類中最大數據類型的整數倍.CPU訪問對齊的數據的效率是最高的,因此通常編譯浪費一些空間來使得我們的數據是對齊的
class A{
public:
int a;
};
class B{
public:
int a ;
char b;
};
class C{
public:
int a ;
char b;
char c;
};
sizeof(A) = 4 (內含一個int ,所以大小爲4)
sizeof(B) = 8 (int爲4,char爲1,和爲5,考慮到對齊,總大小爲int的整數倍即8)
sizeof(C) = 8 (同上)
附:【轉】
1.sizeof操作符的結果類型是size_t,它在頭文件中typedef爲unsigned int類型。
該類型保證能容納實現所建立的最大對象的字節大小。
2.sizeof是算符,strlen是函數。
3.sizeof可以用類型做參數,strlen只能用char*做參數,且必須是以”\0”結尾的。
sizeof還可以用函數做參數,比如:
short f();
printf(“%d\n”, sizeof(f()));
輸出的結果是sizeof(short),即2。
4.數組做sizeof的參數不退化,傳遞給strlen就退化爲指針了。
5.大部分編譯程序 在編譯的時候就把sizeof計算過了 是類型或是變量的長度這就是sizeof(x)可以用來定義數組維數的原因
char str[20]=”0123456789”;
int a=strlen(str); //a=10;
int b=sizeof(str); //而b=20;
6.strlen的結果要在運行的時候才能計算出來,時用來計算字符串的長度,不是類型佔內存的大小。
7.sizeof後如果是類型必須加括弧,如果是變量名可以不加括弧。這是因爲sizeof是個操作符不是個函數。
8.當適用了於一個結構類型時或變量, sizeof 返回實際的大小,
當適用一靜態地空間數組, sizeof 歸還全部數組的尺寸。
sizeof 操作符不能返回動態地被分派了的數組或外部的數組的尺寸
9.數組作爲參數傳給函數時傳的是指針而不是數組,傳遞的是數組的首地址,
如:
fun(char [8])
fun(char [])
都等價於 fun(char *)
在C++裏參數傳遞數組永遠都是傳遞指向數組首元素的指針,編譯器不知道數組的大小
如果想在函數內知道數組的大小, 需要這樣做:
進入函數後用memcpy拷貝出來,長度由另一個形參傳進去
fun(unsiged char *p1, int len)
{
unsigned char* buf = new unsigned char[len+1]
memcpy(buf, p1, len);
}