【问题标题】:What does the & symbol mean in Objective-C?Objective-C 中的 & 符号是什么意思?
【发布时间】:2009-09-04 09:37:31
【问题描述】:

& 符号在 Objective-C 中是什么意思?我目前正在研究数据构造,并且对此感到非常困惑。

我在网上四处寻找,但根本没有找到答案。我知道这可能是一个基本的 Objective-C 概念,但我无法理解它。

例如:

int *pIntData = (int *)&incomingPacket[0];

这里的代码对传入的数据包做了什么?

【问题讨论】:

  • & 是 C 运算符;如果您对 C 还不是很熟悉,那么学习 Objective-C 对您来说可能会很困难。

标签: iphone objective-c syntax operators


【解决方案1】:

& 是一元运算符的 C 地址。它返回其操作数的内存地址。

在您的示例中,它将返回incomingPacket 数组的第一个元素的地址,然后将其转换为int*(指向int 的指针)

【讨论】:

    【解决方案2】:

    在 C 中的意思是一样的。

    int *pIntData = (int *)&incomingPacket[0];
    

    基本上这就是说incomingPacket (&incomingPacket[0]) 的开始地址是一个指向int (int *) 的指针。局部变量 pIntData 被定义为指向 int 的指针,并设置为该值。

    因此:

    *pIntData will equal to the first int at the beginning of incomingPacket.
    pIntData[0] is the same thing.
    pIntData[5] will be the 6th int into the incomingPacket.
    

    为什么要这样做?如果您知道正在流式传输的数据是一个整数数组,那么这可以更容易地遍历整数。

    如果我没记错的话,这句话也可以写成:

    int *pIntData = (int *) incomingPacket;
    

    【讨论】:

      猜你喜欢
      • 2014-04-26
      • 2010-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-24
      • 2014-01-31
      • 2010-09-29
      相关资源
      最近更新 更多