Click to See Complete Forum and Search --> : Converting unsigned char[ ] to const char *
bcyde
September 29th, 1999, 03:21 PM
I was just wondering how to convert a character array to a constant character pointer. Specifically I am using a filename stored in a character array and I get the error that I cannot convert the char [ ] to const char * when I use fopen("name of character array", "rb"). Any help would be appreciated.
GilFisher
September 29th, 1999, 06:00 PM
You should be able to cast the string.
fopen((const char *)"name of character array", "rb").
Actually I would have assumed that putting text in quotes and passed to a function would already be const. Seems like the compiler is a little confused. Maybe someone else will know why the compiler is typeing this a char * instead of const char *.
September 29th, 1999, 06:57 PM
I don't think he had string in quotes, it was just a name of the array.
char myarray[100];
fopen(myarray, "rb");
GilFisher
September 30th, 1999, 09:57 AM
I beleive you are correct, however, the answer is still correct. He needs to cast (const char *)myarray for the compiler to stop complaining about the data not being constant.
September 30th, 1999, 12:14 PM
Not true. The compiler doesn't care whether the data is const or not as an input parameter. Exposure of const on an input parameter is an implementation detail that tells you the function you call won't change it. Even if you pass NON-const versions, the function implicitly converts it to const, because by convention, it cannot modify that data within its scope anyway. No loss of generality.
However, the reason the original poster is having difficulty is because his types are different. A fixed array and a char* are often considered similar except when the char type is defined to be SIGNED instead of UNSIGNED in one place or another, or as a compiler default. Might check that. Otherwise, just a (char*) will suffice.
By the way, if you're using a C++ compiler, you should use static_cast<char*>(var) instead. It's safer.
Good luck,
JH
James Curran
September 30th, 1999, 01:08 PM
JH (second Anon poster) was on the right track, but didn't explain it clearly.
Your problem is because "unsigned char", "signed char" and "char" are three distinct types in C++.
char[] implictly converts to char*.
char* implictly converts to const char*.
but "unsigned char" needs an explict cast to convert to "char".
To further confuse things, a string literal is of type "char[]" and not "const char[]" as you might expect.
Truth,
James
http://www.NJTheater.com
http://www.NJTheater.com/JamesCurran
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.