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) Pointers and Memory Pointer Power

Kingsley Peh
Kingsley Peh
450 Points

Why do we need pointers ?

The codes in the tutorial,

char *letter; char c = ‘k’; letter = &c;

VS

char c = ‘k’;

Why can’t we just output the value of 'c' by just calling 'c' than *letter ? Is there any advantage or specific use case ?

2 Answers

Stone Preston
Stone Preston
42,016 Points

pointers are very useful. since they just hold a memory address, the memory required to pass them around to functions and use them in programs is very small. If you had an array of a whole lot of values, passing that whole array around would be very expensive in terms of memory. With a pointer to that array, all you are passing around is a memory address which is tiny.

Another use of pointers is that they are passed by reference, opposed to non pointers which are passed by value. Passing by reference means that when pointers are used as a functions argument, the value that pointer points to is actually modifies, whereas if you passed a non pointer a copy of that value is created and the function acts on that copy. It doesnt modify the original at all.

When you get into objective C, you will learn that everything (aside from primitive types) are pointers. So you will be using them all the time

Kingsley Peh
Kingsley Peh
450 Points

I see. Thanks for your reply.

So pointers work a lot like variable scope ?

Just that 'scoped' variables are still copies of the original but for pointers, the original value is modified saving memory ?

If that's the case, then why do we even need to use scoped variables anyway ?

Sorry if the questions sound stupid. Haha, am trying to understand pointers inside out.