Cannot convert const char * to char *

Visual Studio C ++ 2005

I get an error in 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 fine

 const char * end_ptr = strstr ( start_ptr, enc_end ); 

So why should I declare end_ptr as const?

Many thanks,

+4
source share
3 answers

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 allows you to call a version that takes const char * as the first parameter, this version also returns const char * , so you need to change the return value to match it,

+13
source

So why should I declare end_ptr as const?

For the same reason that start_ptr must be const char* : strstr returns the type const char* (= char const* ), because it searches inside the constant string (the parameter you pass to strstr is also equal to const char* ). In particular, this is not a pointer, which is const , its memory, which 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 immutable pointer that points to a mutable string, i.e. a line where you can change individual characters.

+2
source

Suppose the return value from strstr was char* , with the first parameter const char* , as in C. Then you can write:

 const char *s = "hello, world"; strstr(s, "hello")[0] = 'j'; 

The code will compile and run (with undefined behavior), but this is the type of error that const was specifically designed to prevent. You converted const char* to char* without a cast.

C can do nothing about it: if strstr returned const char* , then you would need to drop it back to non-constant explicitly if the input is not const and you want to change the line. Since C ++ has an overload function, it can (and does) connect a loophole and make both cases work correctly. Therefore, in C ++, the above code does not compile, and your sample code does too.

+1
source

Source: https://habr.com/ru/post/1303537/


All Articles