weird thing with vectors (C++)
char word[] = {"a", "b", "c", "d"}
when compiling it throws an error. but when I change it for this:
char word[][2] = {"a", "b", "c", "d"}
it compiles well.
Whats wrong with this?? Isnt it the same as
char word[] = {"abcd"}
??
thanks.
"a" is a string containing 2 characters: 'a' and '\0' (the null terminator). So, your array initialisers
are actually 4 strings, not 4 characters.
That's equivalent to
{"a", "b", "c", "d"}
are actually 4 strings, not 4 characters.
{'a', 'b', 'c', 'd'}
would appear to be what you are looking for.Quote:Isnt it the same as char word[] = {"abcd"}
That's equivalent to
char word[] = {'a', 'b', 'c', 'd', '\0'}
Nope. The first line of code you have is attempting to create an array of chars called word, but you're attempting to place strings into it. In C/C++ a char is surrounded by single quotes ('), strings are surrounded by double quotes (")
The reason the second line works is because you are creating an array of char[2] arrays, char[2] is a string containing up to two characters, minus the terminating zero/null character, thus, a single character string is fine to store here.
Its also not the the same as "char word[] = {"abcd"}" because that defines a string of 4 characters 'a', 'b', 'c' and 'd' followed by the terminating character. The former defines 4 individual arrays containing strings of 'a', 'b', 'c' and 'd' each followed by their own terminating character.
What you seem to want is: char word[] = {'a', 'b', 'c', 'd'}
The reason the second line works is because you are creating an array of char[2] arrays, char[2] is a string containing up to two characters, minus the terminating zero/null character, thus, a single character string is fine to store here.
Its also not the the same as "char word[] = {"abcd"}" because that defines a string of 4 characters 'a', 'b', 'c' and 'd' followed by the terminating character. The former defines 4 individual arrays containing strings of 'a', 'b', 'c' and 'd' each followed by their own terminating character.
What you seem to want is: char word[] = {'a', 'b', 'c', 'd'}
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement