Jump to content
  • Advertisement
Sign in to follow this  
freenity

weird thing with vectors (C++)

This topic is 4451 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Advertisement
"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
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!