Sign in to follow this  
freenity

weird thing with vectors (C++)

Recommended Posts

freenity    144
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.

Share this post


Link to post
Share on other sites
bakery2k1    712
"a" is a string containing 2 characters: 'a' and '\0' (the null terminator). So, your array initialisers
{"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'}

Share this post


Link to post
Share on other sites
Ravyne    14300
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'}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this