天天看点

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