Code:
#include <iostream>
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:
原因是數(shù)組作為參數(shù)傳給函數(shù)時(shí),是傳給數(shù)組的地址告嘲,而不是傳給整個(gè)的數(shù)組空間,因而sizeof(a)這句話會(huì)報(bào)錯(cuò)
正確的用法是:不在函數(shù)內(nèi)部使用sizeof
#include <iostream>
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;
}