Implicit conversion of char [] to char * in C ++
Size char[]
is number of char times sizeof(char)
, size char*
is sizeof(pointer)
- a pointer to the first element.
sizeof(char[])
prints number of char times sizeof(char)
to main()
where it is declared, but if I pass this array to work, it converts char[]
to char*
and cannot get the size of the array with sizeof()
,
"void pr(char chr[])" is changed to "void pr(char chr*)"
Sample code:
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 standardized behavior or is the implementation based?
source to share
This is the standard behavior as it involves a function call and [dcl.fct]/5
says:
The type of each parameter (including function parameter packages) is determined from its own seq-qualifier and declarator. After defining the type of each parameter, any parameter of type "array T" or type of function T is configured to be "pointer to T".
so you are printing the size char*
.
Instead of using a link:
void pr(char (&chr)[9])
{
std::cout << "in pr(): " << sizeof(chr)<<"\n";
}
will output again 9
in the second case.
Other suggestions if you are interested in array size:
- Use
std::array
or another container (preferably and read the documentation first to avoid pitfalls such as wasting stack space) - Pass pointer and array size
source to share
You are passing the array as a pointer in both cases (char [] and char *). It is not possible to get additional information about the allocated memory for the array inside the function. You can use an additional parameter about the size or your own typedef of the structure or class, or you can use the STD library.
source to share