Cannot convert const char * to char *
Visual Studio c++ 2005
I am getting an error on the last line of this code.
int Utils::GetLengthDiff ( const char * input, int & num_subst )
{
int num_wide = 0, diff = 0 ;
const char * start_ptr = input ;
num_subst = 0 ;
while ( ( start_ptr = strstr ( start_ptr, enc_start ) ) != NULL )
{
char * end_ptr = strstr ( start_ptr, enc_end ); // Error
So I changed the line to this and it worked ok
const char * end_ptr开发者_JAVA百科 = strstr ( start_ptr, enc_end );
So why would I need to declare end_ptr as a const as well?
Many thanks,
C++ has two overloaded versions of this function. http://www.cplusplus.com/reference/clibrary/cstring/strstr/
const char * strstr ( const char * str1, const char * str2 );
char * strstr ( char * str1, const char * str2 );
Since your start_ptr
is const char *
the C++ compiler resolves to call the version that takes a const char *
as the first parameter, that version also returns a const char *
, so you have to change your return value to match.
So why would I need to declare end_ptr as a const as well?
For the same reason that start_ptr
needs to be const char*
: strstr
returns the type const char*
(= char const*
) because it searches inside a constant string (the parameter you pass to strstr
is also const char*
). In particular, it’s not the pointer that is const
, it’s the memory it points to. Think of it as a pointer to an immutable (i.e. constant) string. You can change what it points to but not the individual characters inside the string.
This is different from an unchangeable pointer which points to a mutable string, i.e. a string where you can change individual characters.
Suppose that the return value from strstr
were char*
, with a const char*
first parameter, as it is in C. Then you could write:
const char *s = "hello, world";
strstr(s, "hello")[0] = 'j';
The code would compile and run (with undefined behavior), but it's the kind of error which const
was specifically designed to avoid. You've converted a const char*
to char*
without a cast.
C can't really do anything about it: if strstr returned const char*
then you'd have to cast back to non-const explicitly in the case where the input is non-const and you want to modify the string. Because C++ has function overloading it can (and does) plug the loophole and make both cases work correctly. Hence in C++, the above code fails to compile, and so does your example code.
精彩评论