0

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.

TriskalJM
  • 2,393
  • 1
  • 19
  • 20
eclipse
  • 2,831
  • 3
  • 26
  • 34

2 Answers2

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 to std::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