简体   繁体   中英

Parameter passing and scope of array in C/C++

This problem has been bugging me since forever. I have an array and in the scope of its declaration, I can use the sizeof operator to determine the number of elements in it but when I pass it to a function, it interprets as just a pointer to the beginning of the array and the sizeof operator just gives me the size of this pointer variable. Like in the following example,

#include<iostream>
int count(int a[]){
    return (sizeof(a)/sizeof(int));
}
int main(){
    int a[]={1,2,3,4,5};
    std::cout << sizeof(a)/sizeof(int) << " " << count(a) << std::endl;
    return 0;
}

The output of the code is 5 2 . How so I pass an array to the function so that I could determine its size by the use of only the sizeof operator and won't have to pass on the extra size as a parameter to this function?

template<size_t N>
int count(int (&a)[N])
{
    return N;
}

You cannot do that. There is no way of passing an array that will make it carry its size information with it. You have to do it yourself. You have to pass the count as an additional parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM