Mohammad yummy
Mohammad yummy

Reputation: 111

Dynamic length of strings in C++

I've debugged some programs in C++ and I notice a difference between for instance :

char str[] = "It's a test";

But when you use string in <string> header, it seems that has a variable length and for instance, the following is allowed:

string str1 = "abcdefg";
str1 = "abc";

But this is not allowed :

char str[] = "It's a test";
str = "abc";

It won't work! What's the implementation behind that?

Upvotes: 3

Views: 3374

Answers (2)

sci3nt15t
sci3nt15t

Reputation: 93

you thought that when at first you have initialised the array of characters and another time when you use it it is not needed to initialise again! but its not true...every time you declare and initialise any array and when ever you are using it again you have to do it again! for example:

char user[] = "sci3nt15t";
char user[] = "Ender";

its good for you to have a look at a definition of string and array.

hope it helps.

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409176

You can initialize an array, which is done with

char array[] = "some string literal";

but you can't assign to an array. That's just the rules of the language.

The std::string class have a special overload for the assignment operator that allows it to be assigned to.

Upvotes: 9

Related Questions