Maxwell
Maxwell

Reputation: 3

Multidimensional array prints hex numbers instead of the contents of the array

I was playing around with multidimensional arrays and was wondering what is happening in this bit of code that makes it print out hexadecimal rather than the actual contents of the array. I understand this might be a silly question but hopefully someone can explain it this is my first year programming.

#include <iostream>

void print(int A[][3],int N, int M)
{
  for (int R = 0; R < N; R++)    // Why when executed does this code output:
    for(int i = 0; i < 4; i++)   //0x61fdf0 0x61fdf0 0x61fdf0 0x61fdf0
    std::cout << A[R] << " ";    //0x61fdfc 0x61fdfc 0x61fdfc 0x61fdfc
  for (int C = 0; C < M; C++)    //0x61fe08 0x61fe08 0x61fe08 0x61fe08
    for(int j = 0; j < 3; j++)   //0x61fe14 0x61fe14 0x61fe14 0x61fe14
    std::cout << A[C] << " ";    //0x61fdf0 0x61fdf0 0x61fdf0 0x61fdfc
}                                //0x61fdfc 0x61fdfc 0x61fe08 0x61fe08 0x61fe08

int main ()
{
  int arr[4][3] ={{12, 29, 11},
                  {25, 25, 13},
                  {24, 64, 67},
                  {11, 18, 14}};
  print(arr,4,3);
  return 0;
}

Upvotes: 0

Views: 202

Answers (1)

cigien
cigien

Reputation: 60238

If you have a 2 dimensional array like int arr[4][3], then arr is essentially just a memory address pointing to the entire 2D array.

Similarly, arr[X] is also an address pointing to one row of the 2D array. So printing either:

std::cout << arr;
std::cout << arr[1];

will print a memory address, which just shows on the screen as a hexadecimal number.

To get to the underlying int, you need to specify both indexes of arr, like this:

std::cout << arr[1][1];  // prints an int

The same thing applies to A in your function, of course.

Upvotes: 1

Related Questions