Hello. Can someone tell me what will happen if i have an array Ar[5][5] and a pointer ptr = Ar[0][0] and try accessing the second line of Ar throught ptr by increasing it by 5? I mean ptr+5 ==Ar[1][5] or something else?

Recommended Answers

All 2 Replies

Hello. Can someone tell me what will happen if i have an array Ar[5][5] and a pointer ptr = Ar[0][0] and try accessing the second line of Ar throught ptr by increasing it by 5? I mean ptr+5 ==Ar[1][5] or something else?

You're almost there. Assuming you had a 5X5 array and your pointer was initially at 0,0. If you increment the pointer by 5 you'll end up at array position 1,0.
Not sure about the code you've got in your post though, if that's pseudo-code, then you're more or less on the ball, but just in case lets try to implement a simple example.
Something like this:
Note: for the sake of brevity I've only used a 2X5 array instead of 5X5.

#include <iostream>
using namespace std;

int main()
{
    int array[2][5]={
        {1,2,3,4,5},
        {6,7,8,9,10},
        };

    int *ptr = &array[0][0];
    cout << "The value at the start of the array is: " << *ptr << endl;
    ptr+=5;
    cout << "The value 5 positions from the start of the array is: " << *ptr << endl;
    return 0;
}

so the first cout should output the value 1 and the second should output 6.

Note: This was just a quick example to show you how pointers work, but it's not a particularly exhaustive or practical example.
Also, when using pointers with arrays in this manner, ensure you do not overstep the boundaries of the array, otherwise you could end up knee deep in the doo doo!
Cheers for now,
Jas.

Or if you want to do a true pointer to a 2D array, like this:

#include <iostream>
using namespace std;

int main()
{
  int array[2][5]={
    {1,2,3,4,5},
    {6,7,8,9,10},
  };
  int (*ptr)[5] = array;
  cout << "The value at the start of row 0 is: " << (*ptr)[0] << endl;
  ptr++;
  cout << "The value at the start of row 1 is: " << (*ptr)[0] << endl;
  return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.