Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Objective-C Basics (Retired) Beyond the Basics Pointers: Part 2

I am a bit confused by the increment function. - how X by itself gives the memory address in the print statement

Pointers

Sérgio Leal Hey Sergio, I still have a doubt as well. Why when we instantiate a new object we have to do so with a pointer but when, printing it or one of its properties we don't need to use the *, since the variable name by itself prints the mem address. Let me illustrate: -- Create object Book: <@>implement Book : NSObject @property(nonatomic, strong) NSString * title; <@>end --When creating an instance of book we use: Book *book = [[Book alloc] init]; --When printing a book or adding a value to its property we just use: book.title = @"Moby Dick"; NSLog(@"%@", book.title) --Why not: *book.*title = @"Moby Dick" NSLog(@"%@", *book.*title); -- The names without * points to the memory right? So shouldn't it print 0x123456 instead of the actual content?

Thank you for your help :)

3 Answers

Let's see if I understood your question right and if I can help.

There's 3 things in a variable that you can think of (know), it's type, value and memory location.

int i = 100;
int *x = &i;

From the code above you know that:

Variable i
type: int (integer number)
value: 100
location: some location in the main memory where this information is stored (let's assume 0x123456)

Variable x:
type: pointer to memory location that stores an integer value
value: the memory address of the variable i (in this example 0x123456)
location: some location in the main memory where this information is stored (let's assume 0x123457)

So in the print statement &x is the memory location of the variable x, and the information stored there is the memory address of the variable i.

Hope this helps.

Martin Shay
Martin Shay
5,919 Points
increment(int *x)

(int *x) can also be written as (int* x), which is more intuitive for me. both mean that x is an integer-pointer/pointer to an integer.

when we pass &i to the increment method, we are assigning the memory address of the integer 'i' to the variable x. x is a pointer to an integer.

x = the memory address of i.

Because x is a pointer that holds the memory address of what it is pointing to. Then you reference or dereference what it is pointing to in order to get that value.