views:

339

answers:

2

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?

+5  A: 

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;
mahboudz
+6  A: 

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

Paul Dixon