I have this code:
int board[3][3]; // I am ommiting initialization code for board here so as not to clutter it.
typedef std::vector<std::pair<int [3][3], int> > History;
History hist = History();
const std::pair<int[3][3], int> p = std::make_pair(board, cell);
hist.push_back(p);
but compiling it with g++ gives me this error which I can’t understand:
In file included from /usr/include/c++/4.7/bits/stl_algobase.h:65:0,
from /usr/include/c++/4.7/vector:61,
from performancesystem.h:29:
/usr/include/c++/4.7/bits/stl_pair.h: In instantiation of
‘std::pair<_T1, _T2>::pair(const std::pair<_U1, _U2>&) [with _U1 =
int (*)[3]; _U2 = int; _T1 = int [3][3]; _T2 = int]’:
Test.cpp:74:65: required from here
/usr/include/c++/4.7/bits/stl_pair.h:111:39: error: incompatible types in
assignment of ‘int (* const)[3]’ to ‘int [3][3]’
I always had this problem understanding the difference between pointers and arrays in C++. Shouldn’t they be the same thing? Can anyone help me please?
Can’t blame you, as the difference of array vs. pointer realizes typically only in dynamically sized structures.
The array int a[3][4][5][6] e.g. is allocated linearly from memory. It contains 3*4*5*6 units and where a[2][3][4][0] … a[2][3][4][5] are in 6 consecutive indices and where a[0][1][n][5] are each 6 elements apart and where a[1][n][3][6] are each 5*6 elements apart and so on.
Pointers however provide ‘indirection’.
The multidimensional array can be implemented by first_level array a[3] providing 3 pointers (indirections) to next level arrays b[4], c[4] and d[4], each of which provide indirection to next level and so on.
In many real life application (e.g. a table of pointer to strings) one really can’t see the difference, as the syntax hides the details:
int main(int ac, char **av) {// one can get third character of third string withav[2][2], even though the prototype can be represented withint main(int ac, char *av[]);, but not withint main(int ac, char av[][]);as the dimension of the table av can’t possibly be determined from that syntax.