Array Matrix

int matrix[2][2], i, j;
for (i=0; i < 2; i++) {
int *ptr = matrix[0] + 2*i;
for (j=0; j < 2; j++)
ptr[j] = (i+1)*(j+1);
}

hey guys, i got across this in one of my past paper questions, however I do not seem to be able to figure this out. Have tried searching for array in matrix but dont seem to understand.

I am suppose to state the value of the array matrix after the code is executed.

thx!!!
If you don't know what that value is, compile it. Is there something you don't understand about this code?
i tried, but i keep getting all sorts of errors, i do not get the matrix, *ptr and ptr bit
thx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

int main(){
    int matrix[2][2], i, j;
    for (i=0; i < 2; i++) {
        int *ptr = matrix[0] + 2*i;
        for (j=0; j < 2; j++)
            ptr[j] = (i+1)*(j+1);
    }
    for(i = 0; i < 2; i++) {
        for(j = 0; j < 2; j++)
            std::cout << matrix[i][j] << " ";
        std::cout << '\n';
    }
    std::cin.ignore();
    return 0;
}
Added output.

Are you familiar with pointers at all?
matrix is a 2x2 array. ptr is a pointer. The thing to understand here is that even though you call it a 2d array, memory is always linear. Every element of the array can be accessed using simple pointer arithmetics.
no I was not, but i've just read quite a bit abt it now. thx a lot!!
now that you've added the the output part, i am completely confused, also for what is the differnce between ptr and *ptr, as i could not find much about this particular pointer function.

Again thx a lot, as i am only a beginner in C++
line 6 (in my code) sets ptr to ith row of matrix.
Here * is only there to show that ptr is a pointer. You could do
1
2
3
typedef int* int_pointer;
...
int_pointer ptr;
It's a part of the type.

In other cases, * returns the value a pointer points to.
1
2
3
4
int a = 5;
int* ptr = &a;
cout << ptr << '\n';//prints 0xSOMETHING
cout << *ptr;//prints 5; 
Topic archived. No new replies allowed.