2D array addresses

Uhm why does looping a 2D array to print it but only using one dimension prints the addresses inside the array instead?

Like
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
int main()
{


    cin >> n >> m;

    int r = n;
    int c = m;
    int matrix[r][c];


    for(int i = 0; i < r; i++)
    {
        for(int j = 0; j < c; j++)
        {
            matrix[i][j] = 0;
        }
    }


    for(int i = 0; i < r; i++)
    {
        for(int j = 0; j < c; j++)
        {
            cout << matrix[i] << " " ;
        }
    }






    return 0;
}


prints:
0x6afe78 0x6afe78 0x6afe78 0x6afe84 0x6afe84 0x6afe84 0x6afe90 0x6afe90 0x6afe90


for a 3x3 array.


But adding the 2nd dimension subscript [j] prints the numbers, what's the concept behind that?


PS: I know int matrix[r][c]; is against the standard cuz the "VLA" but you know..mingw compilers seem to deal with it as if its ok so no comments on dat pl0x xD
Last edited on
Because (C-style) array names are pointers and you're printing the values of pointers (i.e. memory addresses). You probably don't have all compiler warnings turned on as well, otherwise you'd have seen the following against line 25:
1
2

|warning: taking address of array of runtime bound [-Wvla]
matrix[i] is an array (not a pointer). Had there been operator<< defined for arrays (for VLA arrays, in your case), it would be called. However, there is no operator<< for any kind of arrays, so the compiler looks for possible implicit conversions.
There is an operator<< for pointers and there is an implicit conversion from arrays to pointers. This constructs a pointer to the array's first element and that pointer is what gets passed to operator<<. Effectively, you did cout << &matrix[i][0] << " ";

this is similar to how you can call int func(int) with an argument that has type double: an implicit conversion creates an int and calls the function with that int as an argument instead.
Last edited on
As cobbi said, matrix[i] is an array which means it's a pointer to the array's start you could also use the *matrix[i] in order to get the matrix[i][0] element. I recommend to you to not fall for this kind of errors as they are sometimes are to be detected. If you need help detecting those problems you can try programs like checkmarx or others but it's always recommended to learn how to do it on your own.
Good luck!
Beb.
Topic archived. No new replies allowed.