Having a problem with pass by reference in two dimensional array in c++ -
i have variable called names 2 dimensional array. declared below there maximum of 5 names , each name 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 correct passit(names); } void passit(char names[][256]){ printf("%d\n",sizeof(names)/256); //this prints out 8 seems size of pointer } how should change in passit function, number of elements printed correctly?
your code c-style. if you're writing c++ suggest using std::cout, std::vector , 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, can perform intermediate fix existing code.
as you've spotted, when try pass array value decays pointer (char(*)[256] in case) , lose information on size of first dimension.
passing array reference avoids this, except have specify full array type including array dimensions; template argument deduction makes automatic:
template <size_t n> void passit(char (&names)[n][256]) { printf("%d\n", n); }
Comments
Post a Comment