Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is it possible to have an array of strings in C++?

Tags:

c++

arrays

string

When you access elements of an array using array[i], I thought that C++ would take the starting position of the array in memory and add i*sizeof(one array element) and then dereference that address (or do something equivalent to what I just described). However, it seems to me that if you have an array of strings (std::string), each element could be a different size based on the number of characters in the string, so there must be something else going on.

Also, to my understanding, array elements are stored in contiguous memory. If you had strings stored in contiguous memory and then appended more characters to one of them, all of the succeeding strings would have to be moved over.

Can someone explain to me how this works?

like image 365
user724107 Avatar asked May 30 '11 22:05

user724107


1 Answers

The string size is constant, but it (at some level) has a pointer to some non-constant-sized data.

The pointer size is constant, the pointee size is not.

like image 186
GManNickG Avatar answered Sep 18 '22 15:09

GManNickG