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,
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With