0

I have written following code in C++:

#include<iostream>

using namespace std;

int main()

{
    int a[3]={2,3,1};

    int (*ptr)[3];

    ptr=&a;

    for (int i = 0; i < 3; i++)
    {
        cout<<*ptr[i]<<"            "<<ptr[i]<<"            "<<&a[i]<<endl;
    }

}

And my output is as follows:

2            0x61fe04            0x61fe04

6422020      0x61fe10            0x61fe08

2            0x61fe1c            0x61fe0c

I can understand that ptr contains the memory location of the array a as it points to the array.

But the array location(3rd col) and my pointer content (2nd col) is not a match.

and what is *ptr giving me?

2 Answers 2

3

Remember that pointers aren't arrays and arrays aren't pointers. int (*ptr)[3]; is a pointer to a int[3]. When you advance a pointer via +1 then it advances by the size of the pointee. ptr points to a int[3] hence pointer aritmethics advances in steps of sizeof(int[3]).

On the other hand a when decayed to a pointer to the first element of the array, points to an int. When you increment a it advances by sizeof(int).

Now you just need to consider that x[i] is nothing but *(x + i). Hence ptr[i] is out of bounds for any i != 0. ptr is a pointer to a int[3] but it does not point to the first element of an array of int[3].

You get expected output via:

#include<iostream>

using namespace std;

int main()

{
    int a[3]={2,3,1};

    int (*ptr)[3];

    ptr=&a;

    for (int i = 0; i < 3; i++)
    {
        cout<< (*ptr)[i]  << " " << &(*ptr)[i]<<" "<< &a[i]<<endl;
    }
}

Output:

2 0x7fff37933320 0x7fff37933320
3 0x7fff37933324 0x7fff37933324
1 0x7fff37933328 0x7fff37933328
Sign up to request clarification or add additional context in comments.

Comments

1

Add parentheses when accessing to your pointer. * has higher priority than [], so you get incorrect results.

int main()
{
    int a[3]={2,3,1};

    int (*ptr)[3];

    ptr=&a;

    for (int i = 0; i < 3; i++)
    {
        std::cout<<(*ptr)[i]<<"            "<<&(*ptr)[i]<<"            "<<&a[i]<<std::endl;
    }
}

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.