PDA

View Full Version : What... the... heck? Const Char & Chars.


Jones
2006.06.04, 12:08 PM
Ok, I am SO sick of this error. C++ just won't let me compare char's to actual text. In recent code I've had to actually define certain letters I wanted to check for in arrays.

char hello[] = {"h", "w", "w"};

What's wrong with that? Nothing as far as I can tell! But I get 3 errors:


/Users/gareth/desktop/sizeOf Test/main.cpp:5: error: invalid conversion from 'const char*' to 'char'
/Users/gareth/desktop/sizeOf Test/main.cpp:5: error: invalid conversion from 'const char*' to 'char'
/Users/gareth/desktop/sizeOf Test/main.cpp:5: error: invalid conversion from 'const char*' to 'char'


C never did this, why is C++?

Hog
2006.06.04, 12:38 PM
char hello[] = {"h", "w", "w"};

What's wrong with that? Nothing as far as I can tell! But I get 3 errors:


"h" and "w" happen to be const char*s. so {"h", "w", "w"} is actually a const char*[]. You probably want to either do


char hello[][] = {"h", "w", "w"};


or


char hello[] = "hww";

aarku
2006.06.04, 12:55 PM
You want single quotes instead of double quotes for a literal char.

Taxxodium
2006.06.04, 12:56 PM
or

char[] = {'h', 'w', 'w'};

Notice the single quotes.

akb825
2006.06.04, 04:05 PM
Note that if you use the last method, it won't be NULL terminated, so anything you do with the string using anything that assumes it's a standard C string will likely crash.

capzkilla
2006.06.12, 07:47 PM
Note that if you use the last method, it won't be NULL terminated, so anything you do with the string using anything that assumes it's a standard C string will likely crash.
wouldnt adding that fix that then? like this:
char[] = {'h', 'w', 'w', '\0'};

oh and, if you do this:
char[] = {"h", "w", "w"};
Since the compiler "thinks" they are all strings, every character will be automaticly NULL terminated, so you'd be trying to put 3 strings in a char array, while you wanted to put 3 ascii characters in a char array.
As usual with programming, it's the little things that make the difference ;)

akb825
2006.06.12, 07:54 PM
Yes, that would.