Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

objective c - Why don't I declare NSInteger with a *

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

NSInteger *processID = [[NSProcessInfo processInfo] processIdentifier];

returns an actual variable, not its address. To fix this, you need to remove the *:

NSInteger processID = [[NSProcessInfo processInfo] processIdentifier];

You can have a pointer to an NSInteger if you really want one:

NSInteger *pointerToProcessID = &processID;

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...