带入function array size输出为何不同


#include <iostream>
using namespace std;


void sort(int a[])
{
    int b=sizeof(a)/sizeof(a[0]);
    cout<<b<<endl;
}

int main(){
    int a[100]={1,4,2,4,5,2,3};
    int b=sizeof(a)/sizeof(a[0]);
    cout<<b<<endl;
    sort(a);
}

为什么输出array size是100 2,而不是两个100

如果一个函数参数是数组类型,该参数类型自动转换为相应的指针类型。即

void sort(int a[]);
void sort(int a[100]);

自动转换为

void sort(int *a);

数组大小的信息丢失,因为你需要额外用一个参数来传递数组大小

void sort(int a[], int size);

但是如果参数是数组引用类型,那么该参数类型的数组大小信息是被保留的。

void sort(int (&a)[100])
{
    cout << sizeof(a) / sizeof(int) << endl; // 输出100
}

https://en.cppreference.com/w/c/language/array#Array_to_pointer_conversion

When an array type is used in a function parameter list, it is transformed to the corresponding pointer type: int f(int a[2]) and int f(int* a) declare the same function. Since the function's actual parameter type is pointer type, a function call with an array argument performs array-to-pointer conversion; the size of the argument array is not available to the called function and must be passed explicitly:

函数参数虽然写成int a[],但实际传递的是指针,数组不能传递。所以指针的sizeof得到的不是数组长度,而是指针长度

sizeof是C语言的一个运算符,不是函数,虽然用法很像函数,sizeof的作用是用来返回()里面的变量或者数据类型占用的内存字节数。
函数形参是数组时,虽然参数写成了int a[] 实际传递的不是整个数组,而是数组的首地址。也就是说函数传参用数组来传,实际相当于传递的是指针(指针指向数组的首地址)。
所以你void sort(int a[])中的 a 是指针,不是数组,
只有sizeof(数组名)操作的是数组时,才能返回整个数组所占用的内存空间(以字节为单位的)。
如果sizeof(指针)操作的是指针,返回是指针本身所占用的内存空间,在32位系统上,不管指针指向的是整型数据,还是字符型数据,short型数据,long型数据等,指针本身所占的内存字节数均为4。
如果要在函数中用到数组长度就只能在函数外面获取数组长度再传到函数里。

如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

img