0

I successfully entered values to a 2D array without pointers

int main(){ 
    int A[2][3];
    for (int i=0; i<2; i++){
        for(int j=0; j<3; j++){
            A[i][j] = 2*i+3*j;
            cout<<" "<<A[i][j]<<" ";

             }
    cout<<endl;
  }
}

And the output is

 0  3  6 
 2  5  8

Then I tried to reach the same outcome with pointers

int main(){

    int A[2][3];
    int (*p)[3] = A;

    for (int i=0; i<2; i++){
        for(int j=0; j<3; j++){
             *(*A+j)= 2*i+3*j;
             cout<<" "<<*(A[i]+j)<<" ";

        }
         cout<<endl;
     }

}

And the output is

0  3  6
32758  1  0

any idea why I got a different result for the second array?

2
  • 1
    But your second code sample doesn't use p, you are still using A. And of course *(*A+j) is obviously not the same as A[i][j], there's no use of i in the first expression for instance. Commented Jun 13, 2022 at 17:04
  • 1
    BTW [] works perfectly well with pointers. So the correct pointer using code would be p[i][j] = 2*i+3*j; Commented Jun 13, 2022 at 17:05

2 Answers 2

1

This left operand of the assignment expression

*(*A+j)= 2*i+3*j;

does not depend on the index i. In fact it is equivalent to A[0][j]

Thus elements A[1][j] stay uninitialized.

Instead write

for (int i=0; i<2; i++){
    for(int j=0; j<3; j++){
         *( *( A + i) + j )= 2*i+3*j;
         cout<<" "<<*(A[i]+j)<<" ";

    }
     cout<<endl;
 }

Or with using the declared pointer p the program can look the following way

#include <iostream>

int main()
{
    int A[2][3];
    int (*p)[3] = A;

    for ( int i=0; i < 2; i++ )
    {
        for ( int j=0; j<3; j++ )
        {
             *( *( p + i ) + j ) = 2*i+3*j;
             std::cout << " " << *(A[i]+j) << " ";

        }
         std::cout << std::endl;
     }
}

That is the expression *( p + i ) is the same as p[i] and the expression *( *( p + i ) + j ) is the same as p[i][j].

Sign up to request clarification or add additional context in comments.

Comments

0

You are not using the pointer correctly. In fact, you are not even using it at all. p is a pointer to the first int[3] in A. You can use the subscript operator ([]) on it to dereference it, just like you do with A.

#include <iostream>

int main() {
    int A[2][3];
    int(*p)[3] = A;

    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 3; j++) {
            p[i][j] = 2 * i + 3 * j;             // proper dereferencing
            
            std::cout << ' ' << A[i][j] << ' ';  // verify via `A`
        }
        std::cout << '\n';
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.