指针,指向一个int数组给出了相同的地址时,它被作为解除引用 [英] pointer to an int array gives the same address as when it is dereferenced

查看:153
本文介绍了指针,指向一个int数组给出了相同的地址时,它被作为解除引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code:

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

其中。OUPUTS:

which ouputs:

*(j):0x7fff5ab37c7c
j:0x7fff5ab37c7c
&j:0x7fff5ab37c70
&(*j)0x7fff5ab37c7c
*(*j):9

我认为j是一个指向两个整型数组。

I think that j is a pointer to an array of two integer.

和&放大器; g为整个数组的地址

And &g is the address of the whole array.

整个阵列的则J店的地址。

Then j store the address of the whole array.

所以我使用*(J),它将取消引用数组中的第一个元素。

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

但结果表示,*(j)条存储阵列地址相同的值为J

But the result said that *(j) store the array address the same value as j.

我无法弄清楚如何发生的。

I cannot figure out how this happened.

推荐答案

我认为,Ĵ是一个指向数组的指针

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

是,这是。而这也是为什么输出相同的地址输出先按g 会做的原因。在这种情况下,一个数组衰变为指针,这就是为什么即使输出Ĵ产生同样的结果。

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]

因此​​,使用变得等同于使用先按g 直接,就像 *( * j)条变得等同于 * G 。结果
及(* j)条不过是Ĵ,这与一个数组的地址初始化(取自地址腐朽先按g ,即这个数组的第一个元素的地址)。

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?

由于 j的类型 INT(*)[2] 。一个简单的例子:

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);

输出 9

这篇关于指针,指向一个int数组给出了相同的地址时,它被作为解除引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆