pointer to an int array gives the same address as when it is dereferenced

前端 未结 2 900
再見小時候
再見小時候 2021-01-22 07:06

I have the following code:

#include 
using namespace std;
int main()
{
    int g[] = {9,8};
    int (*j)[2] = &g;
    cout << \"*(j):\"         


        
2条回答
  •  独厮守ぢ
    2021-01-22 07:38

    "I think that j is a pointer to an array"

    Yes, it is. And that's also the reason why *j output the same address as outputting g would do. In this case an array decays into the pointer and that's why even outputting j yields the same result.

    The fact that the same address is outputted might make you think that j and *j are the same pointers, however they are not. Their type is different (a fact that actually matters):

    int g[] = {9,8};     // int[]
    int (*j)[2] = &g;    // int (*)[2]
    

    so using *j becomes equivalent to using g directly, just like *(*j) becomes equivalent to *g.
    And &(*j) is nothing but j, which is initialized with an address of an array (an address taken from decayed g, i.e. an address of the first element of this array).

    So why j and *j outputs the same address and *(*j) outputs the value of first element?

    Because of the type of j being int (*)[2]. A simple example:

    int g[] = {9,8};
    int (*j)[2] = &g;     // j points to the first element as well
    cout << *((int*) j);
    

    outputs 9.

提交回复
热议问题