Aaron
Aaron

Reputation: 113

Different ways to make a string?

I'm new to c++ and I'd like to know right from the start,

Does any of these methods of making strings work exactly the same way and give the exact same results always in every case? is there any difference in the result in any of them?

1) char greeting [6] = { 'h','e','l','l','o','\0' };

2) char greeting[] = "hello";

3) #include <string>
   string greeting = "hello";

Upvotes: 1

Views: 149

Answers (2)

Emil Laine
Emil Laine

Reputation: 42828

1) and 2) work exactly the same. Both create a 6-element non-heap-allocated array, and copy the characters 'h', 'e', 'l', 'l', 'o', '\0' to the array at runtime or load time.

3) creates an instance of std::string and calls its constructor which copies the characters 'h', 'e', 'l', 'l', 'o'(, '\0')* to its internal memory buffer. (* The '\0' is not required to be stored in the memory buffer.)

There is another way to declare a string in C++, using a pointer to char:

const char* greeting = "hello";

This will not copy anything. It will just point the pointer to the first character 'h' of the null-terminated "hello" string which is located somewhere in memory. The string is also read-only (modifying it causes undefined behavior), which is why one should use a pointer-to-const here.

If you're wondering which one to use, choose std::string, it's the safest and easiest.

Upvotes: 5

Ziezi
Ziezi

Reputation: 6467

Do these methods of making strings work exactly the same way and give the exact same results always in every case?

The first two are array definitions:

char greeting [6] = { 'h','e','l','l','o','\0' };
char greeting [ ] = "hello";

"work the same" as in the second definition a '\0' is appended implicitly.

As for the third definition:

string greeting = "hello";

A string is a class type object and as such it is more complex than a simple array.

Is there any difference in the result in any of them?

There is a quantitative1 and qualitative2 difference between the first two and the third stemming from the fact that std::string is a class type object.


1. Quantitative: arrays occupy less memory space than string.

2. Qualitative: string provides resource management and many facilities for element manipulation.

Upvotes: 1

Related Questions