Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strrchr causing 'Cannot convert from const char * to char *'

I am trying to compile some code that was given to me that I'm told compiles fine. Perhaps on a different compiler. I am using VS2010 and I have the following line:

char *dot = strrchr(filename, '.');

This causes the compiler error:

"error C2440: 'initializing': cannot convert from 'const char *' to 'char *'

How come? And how do I fix it?

like image 641
zebra Avatar asked Feb 19 '26 18:02

zebra


2 Answers

The error message is pretty clear. strrchr returns a const char*. So you need:

const char *dot = strrchr(filename, '.');

If you really need a char*, you can use strcpy for conversion.

like image 87
Luchian Grigore Avatar answered Feb 22 '26 06:02

Luchian Grigore


C++ has saner versions of strchr and strrchr than C thanks to overloading, so say:

const char * dot = strrchr(filename, '.');

In C, which has no overloading, you only have a single function char * strrchar(const char *, const char *), and it's up to you to decide whether the result is constant or mutable, depending on which type of pointer to feed into the function. C has many such type-unsafe functions.

like image 41
Kerrek SB Avatar answered Feb 22 '26 06:02

Kerrek SB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!