How does a string work?

Jan 21, 2019 at 10:57am
closed account (42TXGNh0)
Inspired by this reply: http://www.cplusplus.com/forum/beginner/248142/3/#msg1094076

So, literally, string is an array of a bunch of character. But what it's different from array is, it can resize itself no matter how many time you want and it the size of it need not be known in compilation time. Out of curiosity, how does string work like which:

1. allows to let its size not to be known in compilation time and
2. can resize itself?
Last edited on Jan 21, 2019 at 10:59am
Jan 21, 2019 at 11:34am
The string class uses dynamic memory allocation to manage the storage of the characters. This allows it to allocate memory when it needs to, to store whatever it's told to store.
Jan 21, 2019 at 11:35am
closed account (42TXGNh0)
How is
dynamic memory allocation
looks like? Are there any examples, please? Thanks.
Jan 21, 2019 at 12:00pm
This should be adequately covered by your texbook. No C++ textbook of any value would fail to include a section about this.

Alternatively, the tutorial on this website as a "Dynamic Memory" section that contains examples.
Jan 21, 2019 at 3:13pm
closed account (42TXGNh0)
Like... this?: https://www.tutorialspoint.com/cplusplus/cpp_dynamic_memory.htm
Jan 21, 2019 at 3:17pm
Yes, that looks like it covers the same ground as the tutorial on this website that I suggested.
Jan 21, 2019 at 3:46pm
You need to know about pointers first though. So if you don't know about pointers, look it up or see the article on this website itself: http://www.cplusplus.com/doc/tutorial/pointers/

There's a page for dynamic allocation too: http://www.cplusplus.com/doc/tutorial/dynamic/
Topic archived. No new replies allowed.