指针和地址,以该指针导致同样的事情 [英] pointer and address to that pointer lead to the same thing

查看:120
本文介绍了指针和地址,以该指针导致同样的事情的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我看到这这些行:

BYTE MessageToProcess[MAX_MESSAGE_LENGTH];
TcpIpPacketHdr *pHdr = (TcpIpPacketHdr*)&MessageToProcess;

我对自己说的第二行必须是这样的:

I said to myself the second line must be like this :

TcpIpPacketHdr *pHdr = (TcpIpPacketHdr*)MessageToProcess;

但是,当我在调试模式PHDR分两个例子检查,以同样的事情MessageToProcess,而有一个&安培; MessageToProcess在第一code之前,因此通常PHDR应包含MessageToProcess的地址,而不是它指向的字节的地址,例如,在messageToProcess的第一个元素

But when I checked in debug mode "pHdr" points to the same thing as "MessageToProcess" in both example, whereas, there is a "&" before MessageToProcess in the first code, so normally pHdr should contain the address of the MessageToProcess and not the address of the byte it is pointing to, for instance, the first element in the messageToProcess.

所以,问题发生了什么事?我们正在处理的指针字节,而不是功能因此增加和放大器;必须改变方程。

So the question What's happening ? we are dealing with pointers to bytes and not functions so adding & must change the equation.

后来在我们使用PHDR像这样code:

Later in the code we are using pHdr like this :

pHdr->size+2

但最初,在第一个code,它包含指针保持的地址到阵列的第一个字节的地址。

But initially, in the first code, it does contain the address of the pointer holding the address to the first byte of the array.

推荐答案

变量 MessageToProcess 是一个数组。它的地方放置在内存中。通过使用&放大器; MessageToProcess 我们在内存中得到地方的地址数组的存储位置。该类型的&放大器; MessageToProcess 字节(*)[MAX_MESSAGE_LENGTH]

The variable MessageToProcess is an array. It's placed somewhere in memory. By using &MessageToProcess we get the address of that place in memory where the array is stored. The type of &MessageToProcess is BYTE (*)[MAX_MESSAGE_LENGTH].

当您使用 MessageToProcess 无需操作人员的地址,就衰变到一个指向第一个元素,即&放大器; MessageToProcess [0] 。该类型是 BYTE *

When you use MessageToProcess without the address-of operator, it decays to a pointer to the first element, i.e. &MessageToProcess[0]. The type of that is BYTE *.

有关简单的东西作为质询所示的例子中,这两个地址是相同的。的区别在于,当你尝试做一些更多的这些指针。例如,如果你做的(安培; MessageToProcess)[1] 您的的获得同样的事情做的时候 MessageToProcess [1]

For something simple as the examples shown in the question, those two addresses are the same. The difference comes when you try to do something more with these pointers. For example if you do (&MessageToProcess)[1] you will not get the same thing as when doing MessageToProcess[1].

要有所显现了,可以说我们有如下定义:

To visualize it somewhat, lets say we have the following definition:

int a[4] = { 0, 1, 2, 3 };

然后,它是这样的:

Then it's something like this:


&a              &a+1
|               |
v               v
+---+---+---+---+
| 0 | 1 | 2 | 3 |
+---+---+---+---+
^   ^
|   |
a   a+1

这篇关于指针和地址,以该指针导致同样的事情的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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