天天看點

C/C++ 數組作為參數傳遞到函數後,使用 sizeof 産生的問題

有時候需要使用 sizeof(g)/sizeof(g[0]) 計算數組的長度(假設有數組 g)。這裡先解釋下為什麼這樣計算:

sizeof(g) : 整個數組占用的位元組數;

sizeof(g[0]) : g[0] 占用的位元組數;

是以 sizeof(g)/sizeof(g[0]) 為數組長度,但是有時候這樣計算會出錯,例如下面這種情況:

#include <iostream>
#include <stdlib.h>
#include <string.h>

using namespace std;

void func(char s[], int n){
    cout<<"----------------- func -------------------"<<endl;
    cout<<"sizeof(s) = "<<sizeof(s)<<endl;
    cout<<"sizeof(s[0]) = "<<sizeof(s[0])<<endl;
    cout<<"The length of s is "<<sizeof(s)/sizeof(s[0])<<endl;
    cout<<"----------------- pointer -------------------"<<endl;
    char *p = NULL;
    cout<<"sizeof(p) = "<<sizeof(p)<<endl;
}

int main()
{
    cout<<"----------------- main -------------------"<<endl;
    char g[] = {'a', 'b', 'c', 'd', 'e'};
    cout<<"sizeof(g) = "<<sizeof(g)<<endl;
    cout<<"sizeof(g[0]) = "<<sizeof(g[0])<<endl;
    cout<<"The length of g is "<<sizeof(g)/sizeof(g[0])<<endl;
    func(g, 3);
    return 0;
}
           

輸出結果:

----------------- main -------------------
sizeof(g) = 5
sizeof(g[0]) = 1
The length of g is 5
----------------- func -------------------
sizeof(s) = 4
sizeof(s[0]) = 1
The length of s is 4
----------------- pointer -------------------
sizeof(p) = 4
           

在上面的輸出中,第一部分 main 輸出的資訊符合預期。但是,将數組 g 作為參數傳遞到函數 func 時,再做同樣的計算,結果就不一樣了,為什麼呢?

因為數組作為函數參數傳遞後,會退化為指針,是以計算 sizeof(s) = 4 ,實質等價于計算 sizeof(char *s) 的大小,指針變量大小為 4 位元組(在 32 位平台上)。sizeof(s[0]) 計算的是第一個字元的位元組大小,即為 1。我們可以看到指針變量 p 計算大小後也為 4。

是以在将數組作為參數傳遞到函數時,注意 sizeof() 的使用,最好的方式是一同傳遞一個數組元素個數的變量,比如上面例子中的 n。

參考文獻:

[1] https://wenku.baidu.com/view/678d1925a5e9856a561260b1.html

[2] https://blog.csdn.net/ljob2006/article/details/4872167