What does the & symbol mean in Objective-C?

醉酒当歌 提交于 2020-01-10 18:44:07

问题


What does the & symbol mean in Objective-C? I am currently looking at data constucts and am getting really confused by it.

I have looked around the web for it but have not found an answer at all. I know this is possibly a basic Objective-C concept, but I just can't get my head around it.

For example:

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

What is the code doing with incoming packet here?


回答1:


& is the C address-of unary operator. It returns the memory address of its operand.

In your example, it will return the address of the first element of the incomingPacket array, which is then cast to an int* (pointer to int)




回答2:


Same thing it means in C.

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

Basically this says that the address of the beginning of incomingPacket (&incomingPacket[0]) is a pointer to an int (int *). The local variable pIntData is defined as a pointer to an int, and is set to that value.

Thus:

*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.

Why do this? If you know the data you are being streamed is an array of ints, then this makes it easier to iterate through the ints.

This statement, If I am not mistaken, could also have been written as:

int *pIntData = (int *) incomingPacket;


来源:https://stackoverflow.com/questions/1378195/what-does-the-symbol-mean-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!