Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is new able to create an array of strings?

I have seen code that uses arrays of strings in the following way.

string *pointer = new string[runtimeAmmount];

I have also seen the individual characters in a string accessed as follows.

string aString = "this";
char bString[] = "that";
bString[3] = aString[3];

The above would result in bString equaling "thas". This would suggest that a string is actually a pointer to the location of the first character. However a string still has member functions accessed as "string.c_str()" meaning it itself as an object does not follow the rules of a pointer. How does this all work?

Note: My original question was to be different but I figures it out typing it out. If someone could still answer my original question just for verification I would appreciate it. My original question is as follows: How can an array of strings be new'd if each string can vary in length throughout its lifetime? Wouldn't the strings run into each other?

The answer I came up with is: Strings contain pointers to C-style arrays in some way and so the objects take up a set amount of space.

OR

Strings are something of the STL template variety which I have yet to actually take the time to look at.

like image 387
user1497468 Avatar asked Dec 06 '22 13:12

user1497468


1 Answers

I will address what is happening in each of the 4 lines of code in your question, but first I should say that your conclusion is not accurate. You are being "fooled" by the operator overloading built into the string class. While it is likely that internally, the string class maintains a C-style character array, this is encapsulated and string is and should be treated as an opaque object, different from a C-style string.

Now for each of your lines:

string *pointer = new string[runtimeAmmount];

In this line, pointer is set to point to a newly-allocated array of (empty) string objects. runtimeAmmount is the number of strings in the array, not the number of characters in a C-style string.

string aString = "this";

This line constructs a new, empty string using the (non-explicit) conversion constructor from the string class: string(const char *). (Note that in a non-construction context, such as aString = "this";, the operator=(const char *) overload of the string class would be used.)

char bString[] = "that";

This is a typical C-string being treated as an array of characters.

bString[3] = aString[3];

This uses the overloaded operator[] of the string class to return a character (reference) and then assign it to the 3rd character spot in the C-style character array.

I hope this helps.

like image 122
Turix Avatar answered Dec 09 '22 03:12

Turix