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.
#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.