‘sizeof’ on array function parameter ‘arr’ will return size of ‘int*’ [-Wsizeof-array-argument]

Code:
#include 
using namespace std;

int Test(int a[], int length, int x){
    
    int length = sizeof(a)/sizeof(a[0]);

    return 0;
}

int main()
{
    int a [] = {1,2,3,4,5,6,7,8,9,10,11,12};

    int length = sizeof(a)/sizeof(a[0]);

    Test(a,length,2); 
    
    return 0;
}
ERROR:
accepted.cpp: In function 'int Test(int*, int, int)':
accepted.cpp:6:9: error: declaration of 'int length' shadows a parameter
     int length = sizeof(a)/sizeof(a[0]);
         ^
accepted.cpp:6:26: warning: 'sizeof' on array function parameter 'a' will return size of 'int*' [-Wsizeof-array-argument]
     int length = sizeof(a)/sizeof(a[0]);
                          ^
accepted.cpp:4:16: note: declared here
 int Test(int a[], int length, int x){
Cause:

原因是数组作为参数传给函数时,是传给数组的地址,而不是传给整个的数组空间,因而sizeof(a)这句话会报错

正确的用法是:不在函数内部使用sizeof

#include 
using namespace std;

int Test(int a[], int length, int x){
    

    return 0;
}

int main()
{
    int a [] = {1,2,3,4,5,6,7,8,9,10,11,12};

    int length = sizeof(a)/sizeof(a[0]);

    Test(a,length,2); 
    
    return 0;
}

你可能感兴趣的:(‘sizeof’ on array function parameter ‘arr’ will return size of ‘int*’ [-Wsizeof-array-argument])