I'm trying my hand at the iPhone course from Stanford on iTunes U and I'm a bit confused about pointers. In the first assignment, I tried doing something like this
NSString *processName = [[NSProcessInfo processInfo] processName];
NSInteger *processID = [[NSProcessInfo processInfo] processIdentifier];
Which generated an error, after tinkeing around blindly, I discovered that it was the * in the NSInteger line that was causing the problem.
So I obviously don't understand what's happening. I'll explain how I think it works and perhaps someone would be kind enough to point out the flaw.
Unlike in web development, I now need
to worry about memory, well, more so than in web development. So when I
create a variable, it gets allocated a
bit of memory somewhere (RAM I
assume). Instead of passing the
variable around, I pass a pointer to
that bit of memory around. And
pointers are declared by prefixing the
variable name with *.
Assuming I'm right, what puzzles me is why don't I need to do that for NSInteger?
Best Solution
NSInteger
is a primitive type, which means it can be stored locally on the stack. You don't need to use a pointer to access it, but you can if you want to. The line:returns an actual variable, not its address. To fix this, you need to remove the
*
:You can have a pointer to an
NSInteger
if you really want one:The ampersand is the address of operator. It sets the pointer to the
NSInteger
equal to the address of the variable in memory, rather than to the integer in the variable.