Considering c++ (or c++11), where I have some array of data with 2*N integers which represent N pairs. For each even i=0,2,4,6,...,2*N it holds that (data[i],data[i+1]) forms such a pair. Now I want to have a simple way to access these pairs without the need to write loops like:
for(int i=0; i<2*N; i+=2) { ... data[i] ... data[i+1] ... }
So I wrote this:
#include <iostream>
struct Pair {
int first; int second;
};
int main() {
int N=5;
int data[10]= {1,2,4,5,7,8,10,11,13,14};
Pair *pairs = (Pair *)data;
for(int i=0; i<N; ++i)
std::cout << i << ": (" << pairs[i].first << ", " << pairs[i].second << ")" << std::endl;
return 0;
}
Output:
0: (1, 2)
1: (4, 5)
2: (7, 8)
3: (10, 11)
4: (13, 14)
ideaone: http://ideone.com/DyWUA8
As you can see, I cast the int pointer to a Pair pointer, such that c++ simply handles that my data is twice the size of an int. And I know, because that is how arrays work, that the data array is aligned in pairs of two sizeof(int)'s. However, I am not sure whether I can assume that a Pair is exactly two sizeof(int)'s and whether the member fields first and second are stored in that order (or alignment). Technically, in a worst case setting I can imagine that compiler stores 2 bytes for first, then 4 of second and then 2 of first (given that int's are 4 bytes), and somehow manages this. Of course, that is probably ludicrous, but is it allowed in c++?
Please note, I don't want to copy all the data to a new array and manually convert it to Pairs. Imho, that's an expensive operation for just syntax sugar.
May I assume the alignment of the Pair class? Does the same hold for structs? Are there other ways?
From what I read here ( How is the size of a C++ class determined? ) it is up to the compiler, and not in the language, of c++ how classes are aligned in memory. Does this mean that I am doomed to copy my data or use nasty syntax? Can I somehow force minimal alignment in the c++ language, or would I need compiler switches?