I have a variable called names
which is a two dimensional array.
I declared it like below so that there will be maximum of 5 names and each name will consist of 256 characters.
int main(){
char names[5][256];
strcpy(names[0],"John");
strcpy(names[1],"Matt");
printf("%d\n",sizeof开发者_如何学编程(names)/256); //this prints out 5 which is correct
passit(names);
}
void passit(char names[][256]){
printf("%d\n",sizeof(names)/256); //this prints out 8 which seems to be a size of pointer
}
How should I change this so that in passit
function, number of elements will be printed correctly?
Your code is C-style. If you're really writing C++ then I suggest using std::cout
, std::vector
and std::string
:
void passit(std::vector<std::string> const& names) {
std::cout << names.size();
}
int main() {
std::vector<std::string> names(5);
names[0] = "John";
names[1] = "Matt";
std::cout << names.size();
passit(names);
}
Otherwise, you can perform an intermediate fix to your existing code.
As you've spotted, when you try to pass an array by value it actually decays to a pointer (char(*)[256]
in this case) and you lose all information on the size of the first dimension.
Passing the array by reference avoids this, except that you now have to specify the full array type including all array dimensions; template argument deduction then makes this automatic:
template <size_t N>
void passit(char (&names)[N][256]) {
printf("%d\n", N);
}
精彩评论