Charr Array Problem

Hi,

I've just started learning C++ and I've run into a bit of a weir issue with a char type array. I understand the three basic ways to initialize a char array

IE

char str1[10] = "Hello World";

or

char str2[] = "Hello World";

or

char str3[20];

cin >> str3;

What confuses me is why you cannot do the following:

char str4[20];

str4 = "Hello World";

This method works for other variable types (int double etc), and for a string variable type. Any ways around this? or explanation for why it will not work? I know I can get around this using string, but I'm curious why it won't work.

Cheers!

Joseph




actually none of those are valid because the [#] tells how many bytes char is expanding to. how you would actually intialize it is char array[20] = {'h', 'e', 'l', 'l', 'o', '', 'w', 'o', 'r', 'l', 'd', '\0'};
i can't remember if it is " or '
This
1
2
3
char str4[20];

str4 = "Hello World";
won't work because you're trying to assign a pointer. 'str4' isn't a pointer so you can't do that. Use strcpy instead: http://www.cplusplus.com/reference/clibrary/cstring/strcpy/

@Aramil of Elixia
The initialzers of the OP are all correct. C/C++ allows it. The problem of char str1[10] = "Hello World"; is that "Hello World" is longer than 10 char.
i did not know that thank you
Topic archived. No new replies allowed.