3

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?

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.