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.
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
stringclass. While it is likely that internally, thestringclass maintains a C-style character array, this is encapsulated andstringis and should be treated as an opaque object, different from a C-style string.Now for each of your lines:
In this line,
pointeris set to point to a newly-allocated array of (empty)stringobjects.runtimeAmmountis the number of strings in the array, not the number of characters in a C-style string.This line constructs a new, empty string using the (non-explicit) conversion constructor from the
stringclass:string(const char *). (Note that in a non-construction context, such asaString = "this";, theoperator=(const char *)overload of thestringclass would be used.)This is a typical C-string being treated as an array of characters.
This uses the overloaded
operator[]of thestringclass to return a character (reference) and then assign it to the 3rd character spot in the C-style character array.I hope this helps.