Can a char*
in C++ receive a string as a parameter? If so how does this work.
Example:
myfunc("hello"); //call
myfunc(char * c)
{ ...
}
How exactly are chars related to strings?
Can a char*
in C++ receive a string as a parameter? If so how does this work.
Example:
myfunc("hello"); //call
myfunc(char * c)
{ ...
}
How exactly are chars related to strings?
The type of the literal "hello"
is const char[6]
, that is an array of characters with space for the string and a null terminating byte.
C++ allows for converting a function argument to another type when passing it. In this case the array type gets converted to pointer type, const char *
, with the pointer referencing the first character with value 'h'
.
C++03 allowed for conversion to char *
, dropping the const
, but it was undefined behavior to actually modify the string. This was done for old-school C compatibility and has been revoked in the new C++11 standard, so your example will not pass a newer compiler.
Incidentally, due to legacy considerations inherited from C, it would make no difference if the function were instead declared as myfunc(char c[6])
. The type of c
would still be char *
.
It wont work as expected in your example. Using strings this way (a pointer to the beginning char) only works if the string is null terminated. This is how the old c_str works. If we have a reference to the first char, we can iterate until we find the terminating character, "\0" to access the entire string.