Passing 3D array as parameter into function in C++14 the right way
An answer to this question on Stack Overflow.
Question
I need some help, I need to pass a rijndael round key into a function as a parameter. The round key is a 3D array which looks like this:
unsigned char rk[11][4][4];
Now I need to input this into a function and make some binary operations to it (so the parameter should be editable). How do I do it the right way? The way I did it was to put it inside a struct and pass the struct to the function. But it is ugly. So now my code looks like this:
typedef struct{
unsigned char rk[11][4][4];
}roundKey;
void addKey(roundKey* rk, ....)
{
some_unsigned_char ^= rk->rk[foo][bar][i];
}
It is ugly and I would like to do it the right way. How should I do it?
Answer
Au contraire, I think you are doing it in one of the best possible ways, I'd just rearrange to make that a full-fledged class. That way we can easily pass it around, add some nice accessor methods to simplify the code, and otherwise do our best to abstract away the 3D nature of the array from most of the code.
class RoundKey {
public:
uint8_t rk[11][4][4];
uint8_t& operator()(int x, int y, int z){
return rk[x][y][z];
}
};
void addKey(RoundKey &rk, ....){
some_unsigned_char ^= rk(foo,bar,i);
}
(Rearrange indices as appropriate.)
Given the simplicity of the class, the compiler's likely to compile it to something that is very similar, if not identical, to what passing the full 3D array around would have given.