2D array represented in 1D

hi, i know this has been asked before, but i cannot understand why pointers are printed, instead of values... I'm considering a 2d array as a 1d array... where i would expect the element a[i][j] to become a[i*number_columns + j]... but instead of the values of the array, their pointers are given as result. any help appreciated. thanks

#include <iostream>
int main()
    int arr[3][5] = {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}};

    std::cout << arr[2][4] << std::endl; // fine, prints 15
    std::cout << arr << std::endl; // fine , prints pointer to initial element of the array

    for (int i=0;i!=3*5;i++)
        std::cout << arr[i] << std::endl; // prints pointers instead of values....starting from pointer arr, then arr+1, arr+2...

    return 0;
arr is an array of 3 pointers arrays.
each of those 3 pointers points to arrays is an array of 5 ints.
Last edited on
thanks kevinkjt2000
arr is an array of 3 pointers

That is wrong: arr is an array of 3 arrays, each of which is an array of 5 ints.

However, there is no operator<< for arrays, but there is operator<< for pointers, so when you pass arr[i] (array of 5 ints) to cout <<, the compiler constructs a temporary pointer to its first element, and that is what's printed.
Cubbi did you just contradict yourself?
There is no operator << for arrays
, but there is a pointer constructed when you pass arr[i]?

So to be precise arr is an array of arrays that typecasts automatically to a pointer if placed in such a situation.
Last edited on
So to be precise arr is an array of 3 const int pointer

No, this is wrong. There are no pointers in arr.

there is a pointer constructed when you pass arr[i]?

Yes, it is the same as with any type mismatch, for example if you have a double, you can pass it into a function that expects an int.
Thanks Cubbi, you are right. I went and learned a lot about types and in that article I linked to the second post has code that did not compile when I tried it for myself.

I would really enjoy reading a nice article on this subject if someone would be kind of enough to send me a link. I'm still confused on whether or not arrays are const pointer because they behave exactly like a const pointer if put in such a situation. Such as,
int arr[3][5];
*(*(arr + 1) +3) = 800;
Topic archived. No new replies allowed.