简体   繁体   中英

difference between typecasts (int**) and int(*)

In the following piece of code i see that

int i=2;int j=3;
int* arr[]={&i,&j};

cout<<*&arr[0]<<endl; //its arr[0] i.e. &i
cout<<(int*)&arr[0]<<endl;  //address of 1st element of arr.
cout<<(int**)&arr[0]<<endl; // same as above even though now typecasted to int**
cout<<*(int**)&arr[0]<<endl; // this prints the address of arr[0] in hex
cout<<*(int*)&arr[0]<<endl; //this prints the address of arr[0] in int.

Questions:

  1. What does the following mean:

    a. Meaning and Difference between (int**)&arr[0] and (int*)&arr[0]

    b. Meaning and Difference between *(int**)&arr[0] and *(int*)&arr[0]

  2. Why *(int**)&arr[0] and *(int*)&arr[0] prints address in hex and int respectively?

Integers are typically printed in base 10, while pointers are printed in base 16, which explains the difference in outputs you're observing:

First off:

(int**)&arr[0] is a pointer to a pointer to an integer

(int*)&arr[0] is a pointer to an integer

Both of these are pointers, so they are printed as hexadecimals.

Then:

*(int**)&arr[0] is a pointer to a pointer to an integer, dereferenced once. In other words, it's a pointer.

*(int*)&arr[0] is a pointer to an integer, dereferenced once. In other words, it's an integer.

Finally:

*&arr[0] is a pointer to a pointer to an integer, dereferenced once. In other words, it's a pointer to an integer.

The fact that the array is an array of pointers is only relevant to this case, because in each of the prior cases the first thing you do is cast the value of &arr[0] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM