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

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

In addition, as I understand it, the elements of the array are stored in continuous memory. If you had lines stored in continuous memory, and then more characters were added for one of them, all subsequent lines should be moved.

Can someone explain to me how this works?

+3
source share
7 answers

The size of the string is constant, but at (some level) there is a pointer to some data of not constant size.

The size of the pointer is constant, the size of the pointer is not equal.

+5
source

std::strings- objects. The size of one is the std::stringsame as the size of the other std::string. They indirectly "contain" their data through dynamic allocation, which does not affect the size of the owner object.

Similarly, if you mean C-style strings, you actually only go through char*(or pointers-to-char). Pointers are always the same size, regardless of the length of the memory block that they point to.

+4
source

std::string char*, . , , char* . char*, std::string . sizeof(std::string) , .

+2

++ std::string, . , , .

( ), std::string :

struct string
{
  size_t length;
  const char* data;
  // other members..
};

, (a size_t ), , , , .

+1

.. , ++ , . string , , . , , complier .

+1

, (char *) - (char *). , . , :

char foo[10][10];

char foo2[100];

, ; , std::string C-, , , , C . ( std::string , (char *) -, - std::string . )

0

Here's how you do it in code ...

const int ARRSIZE = 5;
string arrayOfStr[ARRSIZE] = {"one", "two", "three"};

for (int i = 0; i < ARRSIZE; ++i)
{                 
    cout << arrayOfStr[i] << endl;                  
}
0
source

All Articles