How is the data of std::vector<std::array<char, 2>>
laid out in memory? Could I recast the vector to std::vector<char>
and access the contents of the arrays that way? I assume this is not the way it works, but since it is C++, I wanted to make sure. If it works the same way as std::vector<std::vector<char>>
, I do not need an explanation since this explains it pretty well.
Asked
Active
Viewed 102 times
0
-
1`vector
` differs from `vector – geza Sep 14 '17 at 20:52`. `vector ` is contiguous, `vector ` is not.
2 Answers
3
std::vector
has less trivial layout than std::array
does. You're trying to cast vector to a vector of a different type, even of a different size. No luck.

bipll
- 11,747
- 1
- 18
- 32
-1
Could I recast the
vector
tostd::vector<char>
and access the contents of the arrays that way?
No, you can't. std::vector
has richer semantics than plain old arrays and pointers. If you call any member function, it will lead to undefined behavior.
However, you can access the array as though it were an array of char
with size size of the vector * 2
iff your implementation of std::array
does not use any padding. i.e. sizeof(array<char, 2> == sizeof(char[2])
.
In that case you can use:
char* cp = &(thevector[0][0]);
to access the contents of the array.

R Sahu
- 204,454
- 14
- 159
- 270
-
5I think std::array is not forbidden from having some padding at the end. At least that used to be the case in C++11. – juanchopanza Sep 14 '17 at 20:56
-
-
If you have some evidence that this is now allowed, please answer the question this is a dupe of. – Ben Voigt Sep 14 '17 at 21:02
-
I found this "This container is an aggregate type with the same semantics as a struct holding a C-style array T[N] as its only non-static data member." here: http://en.cppreference.com/w/cpp/container/array – eclipse Sep 14 '17 at 21:04
-
-
-
3@eclipse, unfortunately, that still does not stop an implementation from using padding. – R Sahu Sep 14 '17 at 21:11