Navigating 2D array with pointer arithmetic - Why does this example work

Viewed 23
int* A= new int [l*m];

for (int i = 0; i<l;i++) {
    for (int j=0;j<m;j++){      
        *(A +i*m+j)=(rand()%9)+1;}}

    for (int i = 0; i<l;i++) {
         for (int j=0;j<m;j++){      
            cout<<*(A+i*m+j)<<" ";}
        cout<<endl;

Output of this would a 2D array size of [l][m] (will be entered through cmd line) filled with random numbers 1-9. I'm placing just an excerpt here so it's easier to read.

Why does *(A+i*m+j) work to move through a 2D array both vertically and horizontally(with for loops ofc) and could it be written differently, this syntax is confusing me?

This was for school, I know I could have done the same with an array of pointers but I really want to understand this bit of code.

Also how do I pass this 2D array as an argument to a function?

As in void arrayFunct(???){}

Thanks in advance.

1 Answers

I think I've figured it out, so if someone should stumble upon this thread, here's the answer I think.

It works because the first step is *(A +0+0) which is the first element of the aray. Then for every increment the pointer moves i times M because M defines how many columns the rows will have a number in. +j is incrementing the columns and in pointer arithmetic, incrementing by one means moving the size of the data type, which is 4B since it's an int type, therefore it goes to the next element.

Related