Reputation: 1886
Size of char[]
is number of char times sizeof(char)
,
size of char*
is sizeof(pointer)
- Pointer to first element.
sizeof(char[])
prints number of char times sizeof(char)
in main()
, where it's declared, but if I pass this array to function, it function converts char[]
to char*
and it's imposibble to get size of array using sizeof()
,
"void pr(char chr[])" is changed to "void pr(char chr*)"
Code example:
using namespace std;
void pr(char chr[])
{
std::cout << "in pr(): " << sizeof(chr)<<"\n";
}
int main()
{
char* c;
char z[] = { 1,2,3,4,5,6,7,8,9};
c = z;
std::cout << "sizeof char* c in main(): " << sizeof(c) << "\n";
std::cout << "sizeof char* c "; pr(c); std::cout << "\n";
std::cout << "sizeof char z[] in main(): " << sizeof(z) << "\n";
std::cout << "sizeof char z[] "; pr(z); std::cout << "\n";
getchar();
return 0;
}
Output:
sizeof char* c in main(): 4 // pointer size
sizeof char* c in pr(): 4 // pointer size
sizeof char z[] in main(): 9 // elements*sizeof(char)
sizeof char z[] in pr(): 4 // pointer s
Is this behavior standardized or its implementation based?
Upvotes: 3
Views: 934
Reputation: 43662
This is standard behavior since there's a function call involved and [dcl.fct]/5
says:
The type of each parameter (including function parameter packs) is determined from its own decl-specifier-seq and declarator. After determining the type of each parameter, any parameter of type “array of T” or of function type T is adjusted to be “pointer to T”.
so you are printing the size of char*
.
Using a reference instead:
void pr(char (&chr)[9])
{
std::cout << "in pr(): " << sizeof(chr)<<"\n";
}
would again output 9
in your second case.
Other suggestions if you're interested in the size of the array:
std::array
or another container (preferred and do read the documentation first in order to avoid pitfalls like wasting stack space)Upvotes: 5
Reputation: 11
You are passing the array as a pointer in both cases (char [] and char *) Inside the function there is not possible to get extra info about the allocated memory for the array. You can use extra parameter about the size or your own typedef of struct or class or you can use STD library.
Upvotes: 1