Reputation: 499
To access any random index in array, we access the following memory location :
a[i] = base address + (size of data_type) * i
This is the reason why arrays have only same type of data.
Now this works perfectly fine when we're working with primitive data types like int, char etc.
However, let's say I have an array of strings where size of each string is different :
string a[] = {"xyz", "abcde", "qwerty"}
How does this work inside memory? Since each string is taking different memory, how does this work out internally?
Edit :
Got the answer for strings. Strings have a constant size internally so it works out.
What happens in case of let's say array of vectors:
vector<int> v[5];
Do they also have a constant size internally?
Upvotes: 1
Views: 726
Reputation: 8064
I'd say string memory layout is implementation dependent but you should generally have something like 15 bytes (for short string implementation) plus a pointer (for larger strings). So an array of std::string
would be a fixed-size, contiguous array of strings (each 15 bytes plus the size of the pointer in my example, usually 4 bytes)
You can do this simple test: print the address of each string in your array, and then print the address of the first character in each string.
#include <iostream>
#include <string>
int main()
{
std::string a[] = {
"Hey",
"There",
"The quick fox jumped over the brown dog",
"Bye!"
};
std::cout << a << "\n";
for (const auto& str : a)
{
std::cout << &str << "\n";
const int* ptr_to_first_char = reinterpret_cast<const int*>(&(str[0]));
std::cout << "\t" << ptr_to_first_char << "\n";
}
}
Results for gcc:
0x7ffc46eef050
0x7ffc46eef060
0x7ffc46eef070
0x7ffc46eef080
0x7ffc46eef090
0x13e8eb0
0x7ffc46eef0b0
0x7ffc46eef0c0
std::string("There")
.https://godbolt.org/z/4zK3c66Mx
Upvotes: 2