关于#c++#的问题:同样一个参数传到函数里面为什么长度就发生变化了

img

求解答!C➕➕里面没有直接数组的长度的方法,所以我就这么用,但是有个问题是:
同样一个参数传到函数里面为什么长度就发生变化了?

数组作为参数传递到函数时,不能通过sizeof来计算数组的大小。而在数组定义的函数内是可以的。
因为数组作为参数,实际是当做指针类型来处理的

数组作为函数参数传递时,会隐式转化为指向第一个元素的指针类型,因此数组大小信息丢失。
https://en.cppreference.com/w/cpp/language/array#Array-to-pointer_decay

There is an implicit conversion from lvalues and rvalues of array type to rvalues of pointer type: it constructs a pointer to the first element of an array. This conversion is used whenever arrays appear in context where arrays are not expected, but pointers are.

当把数组传递给函数时,一般需要额外传递一个数组大小参数,比如:

void f(int a[], size_t size) { // 这里的a是int*类型指针
    // ...
}
int main() {
    int a[] = {1, 2, 3, 4, 5};
    f(a, sizeof(a)/sizeof(int)); // 数组a隐式转化为int*指针类型
}

如果数组大小是固定的话, 你也可以改为引用类型,比如:

void f(int (&a)[5]) { // 这里a是引用类型,sizeof(a)/sizeof(int)返回的是5
    // ...
}
int main() {
    int a[] = {1, 2, 3, 4, 5};
    f(a); // 形参是引用类型,绑定实参数组a,引用类型不会退化成指针。
}