2

I have 5 different 2d Arrays in contrast to the normal usage of 2d Arrays.

int A[1][2] = {2, 5};
int B[1][2] = {6, 1};
int C[1][2] = {4, 8};
int D[1][2] = {3, 6};
int E[1][2] = {9, 7};

Then I have declared an array of Pointers to these 5 arrays by:

typedef int (*PointerToArrays)[2];
static PointerToArrays arr[POPULATION_SIZE] = {A, B, C, D, E};

Now I want to print the elements of these arrays by the following method:

for(int i=0; i<10; i++) {
    for(int j=0; j<2; j++) {
        cout << (*arr)[i][j] <<endl;
    }
}

But I am getting the following results:

2
5
4197162
0
6
1
4197245
0
4
8

You can see that the 1st and 2nd elements are fine, then the next two are garbage. Then the next two are fine and next two are garbage and so on...

What am I doing wrong? How to I print out the values of A, B, C, D and E respectively using a "for" loop?

Mohammad Sohaib
  • 577
  • 3
  • 11
  • 28
  • The expression `(*arr)[i][j]` is equivalent to `arr[0][i][j]`. Now, `arr[0]` is pointing to an array of *one* array of two integers, and yet you use it as an array of *ten* arrays of two integers. – Some programmer dude Mar 03 '16 at 12:17
  • So I should use it as `arr[0][i][j]` instead? And then increment to `arr[1][i][j]`..? – Mohammad Sohaib Mar 03 '16 at 12:19
  • 2
    You should have the outer loop go up to 5 (`arr` only has five elements) and use `arr[i][0][j]`. `arr[0]` is pointing to `A`, and you would not expect `A[9][0]` to work would you? – Some programmer dude Mar 03 '16 at 12:20
  • It works fine now. But I wanted to get something else out of this. I want for each element of arr to have 5 elements. e.g `arr[0] = {A, B, C, D, E}` and `arr[1] = {B, C, A, E, D}` and so on... Is that possible? If yes, how do I do that? – Mohammad Sohaib Mar 03 '16 at 12:29
  • @MohammadSohaib That's yet another level of indexing; `PointerToArrays arr[number_of_elements][POPULATION_SIZE] = {{A,B,C,D,E}, {B,C,A,E,D}...`. – molbdnilo Mar 03 '16 at 12:33
  • Is that a good approach to this problem? Or should I do something else? – Mohammad Sohaib Mar 03 '16 at 12:34
  • 3
    We don't even know what problem you are trying to solve, so we can't say if it's a good approach or not. Please [read about the XY problem](http://xyproblem.info/). – Some programmer dude Mar 03 '16 at 12:35
  • This question should be tagged [c] and not [c++], such use of arrays in the latter language is quite unidiomatic. – Alberto M Mar 04 '16 at 11:21

0 Answers0