Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 = strstr ( start_ptr, enc_end ); 

So why would I need to declare end_ptr as a const as well?

Many thanks,

like image 842
ant2009 Avatar asked Dec 05 '22 03:12

ant2009


2 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 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.

like image 176
John Knoeller Avatar answered Dec 28 '22 23:12

John Knoeller


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.

like image 30
Konrad Rudolph Avatar answered Dec 29 '22 01:12

Konrad Rudolph