0

I am learning 2d array pointers and here is my code. I donot know why this line:

cout<<"Address of 1st part = "<<*ptr`  

is not showing an address while this line is showing me address:

cout<<"Address of 1st part = "<<*(A)`  

These both lines means same can any one help me.

#include <iostream>
using namespace std;


int main()
{
    int A[2][3]={{1,2,4},{5,8,3}};

    int *ptr;
    ptr=&A[0][0];

    cout<<"Address 1st part = "<<A<<endl;
    cout<<"Address 2nd part = "<<A+1<<endl;

    cout<<"Address 1st part = "<<ptr<<endl;
    cout<<"Address 2nd part = "<<ptr+1<<endl;

    cout<<"Address of 1st part = "<<*(A)<<endl;
    cout<<"Address of 1st part = "<<*ptr<<endl;

    cout<<"Address"<<*(A+1)+1<<endl;

    cout<<*(A+1)+2<<endl;

    return 0;
}

output

Address 1st part = 0x7fffb6c5f660 
Address 2nd part = 0x7fffb6c5f66c 
Address 1st part = 0x7fffb6c5f660 
Address 2nd part = 0x7fffb6c5f664 
Address of 1st part = 0x7fffb6c5f660 
Address of 1st part = 1 
Address0x7fffb6c5f670 
0x7fffb6c5f674
9
  • Please narrow it down and show us the output. Commented Jan 26, 2014 at 19:49
  • Address 1st part = 0x7fffb6c5f660 Address 2nd part = 0x7fffb6c5f66c Address 1st part = 0x7fffb6c5f660 Address 2nd part = 0x7fffb6c5f664 Address of 1st part = 0x7fffb6c5f660 Address of 1st part = 1 Address0x7fffb6c5f670 0x7fffb6c5f674 Commented Jan 26, 2014 at 20:06
  • not in a comment, edit your question and format it properly. Commented Jan 26, 2014 at 20:11
  • Because the don't mean the same thing. *ptr resolves to type int. *(A) resolves to type int (&)[3]. they're not even close. Commented Jan 26, 2014 at 20:17
  • thats what the output is Commented Jan 26, 2014 at 20:17

1 Answer 1

1

Those two lines do not actually mean the same. A multi-dimensional array is not equivalent to a pointer to its primitive type.

A is of type int [2][3], which is equivalent to int *[3]. The type of *A is int[3], not int. The step between successive pointed-to elements, sizeof *A, is equal to sizeof(int)*3.

ptr is of type int *. The type of *ptr is int. The step here, sizeof *ptr, is equal to sizeof(int).

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

2 Comments

Please just correct my code the line .. I just want to understand the declaration pointer variable for 2d array. I understood your point please further explain it.
You could write int (*ptr)[3], but I'm not entirely sure what you want to do.

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.