1

Hi Im just starting to get my head around pointers and arrays and Ive more or less know how to manipulate pointers in a one dimensional arrays to display the elements. But how about in multidimensional arrays? I have been practicing with this code:

#include<iostream>
using namespace std;
int main()
{

    int a[2][3]= { {1,2,3},{4,5,6}};
    int (*ptr)[3] = &a[0]; // or (*ptr)[3] = a;

    cout <<"Adress 0,0: "<< a << endl;
    cout <<"Adress 0,0: "<< ptr << endl;         
    cout <<"Value 0,0: "<< *a[0] << endl;
    cout <<"Value 0,0: "<< *(ptr)[0]<< endl;
    cout <<"Adress 0,1: "<< &a[0][1] << endl;
    cout <<"Adress 0,1: "<< (ptr)[1] << endl;       

    return 0;
}

I have managed to display the address and value of a[0][0] using the array name and the pointer, but how to display the address and value of a[0][1] and the succeeding elements by using the pointer?

2
  • (ptr)[1] doesn't point to a[0][1], it points to a[1][0]. Commented Feb 10, 2015 at 17:30
  • I think you're trying to hit (*ptr)[1] if you're looking to deliver the value 2 from your array of arrays. The address of that element is simply (*ptr)+1 (or, if you want to be long-winded, *(ptr+0) + 1 Commented Feb 10, 2015 at 17:31

2 Answers 2

1

(ptr)[1] (same as ptr[1]) doesn't point to a[0][1], it points to a[1][0] because you defined ptr as a pointer to int[3], not int. Therefore incrementing ptr by 1 with ptr[1] skips three ints, up to a[1][0].

To increment ptr by the size of one int instead of three ints:

ptr[0] + 1

The above will point to a[0][1]. And to access that:

*(ptr[0] + 1)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @zenith for clarifying. Yup my previous code pointed (or skipped) 3 ints ahead thats why it printed 4 instead of 2.
1
    #include<iostream>
    using namespace std;

    int main()

{

    int a[2][3]= { {1,2,3},{4,5,6}  };
    int (*ptr)[3] = &a[0]; // or (*ptr)[3] = a;

    cout <<"Adress 0,0: "<< a << endl;
    cout <<"Adress 0,0: "<< ptr << endl;         
    cout <<"Value 0,0: "<< *a[0] << endl;
    cout <<"Value 0,0: "<< *((ptr)[0]+0)<< endl;
    cout <<"Adress 0,1: "<< &a[0][1] << endl;
    cout <<"Adress 0,1: "<< (ptr)[0]+1 << endl;       
    cout <<"value 0,1: "<<  a[0][1] << endl;
    cout <<"value 0,1: "<< *((ptr)[0]+1) << endl;

    cout <<"Adress 1,0: "<< &a[1][0] << endl;
    cout <<"Adress 1,0: "<< (ptr)[1] << endl;       
    cout <<"value 1,0: "<<  a[1][0] << endl;
    cout <<"value 1,0: "<< *((ptr)[1]+0) << endl;       

    return 0;
}

Hope this clears your doubt.

1 Comment

Thank you for your clarification, I now understand how to traverse a 2 dimension array using pointers.

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.