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

前端 未结 2 917
再見小時候
再見小時候 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:29

    I think that j is a pointer to an array of two integer.
    And &g is the address of the whole array.

    That is correct.

    And so I use the *(j), it will dereference the first element in the array.

    This is not. *j gives you the array itself. When you insert it to cout, it decays to a pointer again (this time to a pointer to its first element, type int*) and its value is printed.

    It's in effect the same as if you wrote cout << g.

提交回复
热议问题