Reputation: 463
I just started learning C++ and I was trying to output a string through printf. It wouldn't work because I had to convert the string into a char array first. I googled it and it seems that the best solution was this:
char *a = &b[0];
I somewhat understand it: It's getting a reference to the first character and setting a to that. The part that I don't understand is that this only makes sense to me if the string is stored on the stack, which I know it sometimes can be. If the string is on the heap, what exactly will the [0] index return? Does it return the pointer to the first index, because then the & isn't necessary is it? If it returns the character, doesn't that character take the form of a single value on the stack, which, when referenced, wouldn't give you the correct char array?
Upvotes: 0
Views: 112
Reputation: 7324
The thing to note is that operator[]
returns a reference.
reference operator[]( size_type pos );
Returns a reference to the character at specified location pos.
This is important because it means that b[0]
is essentially an alias to the first character in the string. Taking its address will then give you a pointer to the underlying buffer the string's data is stored in. It doesn't matter where it is (stack, heap, etc). This is also what lets you modify the string's data by using e.g. b[0] = 'a';
.
Note that you can also use c_str()
and data()
to get a pointer to the first character in the string. Since C++17 data()
can return a non-const pointer.
Upvotes: 3