【C++中传递数组到函数时求数组长度问题】

学习记录:

最近学习c++时遇到传递数组到函数的问题,将数组作为实参传递给函数时,传递的是数组首地址,对形参使用sizeof()函数会返回数组地址的长度(此处地址长度为8)。

问题描述

学习场景:
学习左神刷题挑战时,练习选择排序时遇到:

#include<iostream>
using namespace std;
class Mysort
{
    public:
    void Dosort(int a[],int len);
};

void Mysort::Dosort(int a[],int len)
{   
    cout<<"对形参数a求sizeof:"<<sizeof(a)<<endl;
       for(int i=0;i<len-1;i++)
    {
        int maxindex=i;
        for(int j=i+1;j<len;j++)
        {
            maxindex = a[j]>a[maxindex] ? j :maxindex;
        }
        if(maxindex!=i)
        {
            int temp =a[maxindex];
            a[maxindex]=a[i];
            a[i]=temp;
        }
    }
    cout<<"排序结果:"<<endl;
    for(int i =0;i<len;i++)
    {
        cout<<a[i]<<" ";
    } 
}
int main()
{    
    int a[]={1,5,8,4,6,9,3};
    int len=sizeof(a)/sizeof(a[0]); 
    Mysort sor;
    sor.Dosort(a,len);
    return 0;
}

	
//结果:
xuanze.cpp: In member function 'void Mysort::Dosort(int*, int)':
xuanze.cpp:11:41: warning: 'sizeof' on array function parameter 'a' will return size of 'int*' [-Wsizeof-array-argument]
     cout<<"对形参数a求sizeof:"<<sizeof(a)<<endl;
                                         ^
xuanze.cpp:9:25: note: declared here
 void Mysort::Dosort(int a[],int len)
                     ~~~~^~~
对形参数a求sizeof:8
排序结果:
9 8 6 5 4 3 1

原因分析:

数组传递参数时传递的是首地址,对指针求长度得到的是地址长度。


解决方案:

在传递前进行数组长度求解,然后再将数组与长度一起传递。