7

I realize 99% of you think "what the h***…" But please help me to get my head around the this concept of using pointers. I'm sure my specific question would help lots of newbies.

I understand what pointers ARE and that they are a reference to an adress in memory and that by using the (*) operator you can get the value in that address.

Let's say:

int counter = 10;
int *somePointer = &counter;

Now I have the address in memory of counter, and I can indirectly point to its value by doing this:

int x = *somePointer;

Which makes x = 10, right?

But this is the most basic example, and for this case I could use int x = counter; and get that value, so please explain why pointers really are such an important thing in Objective-C and some other languages... in what case would only a pointer make sense?

Appreciate it.

bdesham
  • 15,430
  • 13
  • 79
  • 123
NickCave
  • 79
  • 1
  • 2
  • 3
    A pointer is not a reference to an address. You may say that a pointer is a reference to memory, or that it is a reference to a variable, but it *is* an address. (Technically, a pointer is a variable, and its value is an address. English is ambiguous.) – William Pursell Feb 20 '13 at 23:07
  • 4
    One does not simply statically allocate objects. – CodaFi Feb 20 '13 at 23:11
  • You might want to start there: http://stackoverflow.com/questions/5203284/objective-c-and-pointers/5203296#5203296 – w-m Feb 20 '13 at 23:13
  • @CodaFi You nailed that one down. –  Feb 20 '13 at 23:13
  • Try and write a method for swapping 2 ints without using pointers. – Ben Trengrove Feb 20 '13 at 23:14
  • There are only a handful of languages which don't implement a pointer of some form. Without pointers your capabilities are extremely limited. Without pointers you cannot have objects. – Hot Licks Feb 20 '13 at 23:20
  • @HotLicks I dont understand why book authors dont just say it straightforward "You wouldn't be able to create objects without pointers" and they all giving you the example that only make understand how it works, but this example could work simply with regular variables...A GOOD example is worth a whole chapter on pointers – NickCave Feb 20 '13 at 23:27
  • 1
    @NickCave - Of course, pointers existed a long time before "objects", in any formal sense. But pointers were kind of necessary to the lingo that eventually produced objects, kind of like how the invention of zero revolutionized mathematics. (Though it didn't take that long to invent pointers. They weren't there on day one, but were by about day 3.) – Hot Licks Feb 20 '13 at 23:35

4 Answers4

5

Objective-C has pointers because it is an evolution of C, which used pointers extensively. The advantage of a pointer in an object-oriented language like Objective-C is that after you create an object, you can pass around a pointer to the object instead of passing around the object itself. In other words, if you have some object that takes up a large amount of storage space, passing around a pointer is a lot more memory-efficient than passing around a copy of the object itself. This may not be noticeable in simple cases when you’re only dealing with primitive types like ints, but when you start dealing with more complex objects the memory and time savings are enormous.

More importantly, pointers make it much easier for different parts of your code to talk to each other. If variables could only be passed to functions “by value” instead of “by reference” (which is what happens when you use pointers), then functions could never alter their inputs. They could only change the state of your program by either returning a value or by changing a global variable—the overuse of which generally leads to sloppy, unorganized code.

Here’s a concrete example. Suppose you have an Objective-C method that will parse a JSON string and return an NSDictionary:

+ (NSDictionary *)parseJsonString:(NSString *)json
                            error:(NSError **)error;

The method will do the parsing and return an NSDictionary if everything goes okay. But what if there’s some problem with the input string? We want a way to indicate to the user (or at least to the programmer) what happened, so we have a pointer to a pointer to an NSError, which will contain that information. If our method fails (probably returning nil), we can dereference the error parameter to see what went wrong. What we’ve effectively done is to give our method two different kinds of return values: usually, it will return an NSDictionary, but it could also return an NSError.

If you want to read more about this, you may have better luck searching for “pointers in C” rather than “pointers in Objective-C”; pointers are of course used extensively in Objective-C, but all of the underlying machinery is identical to that of C itself.

bdesham
  • 15,430
  • 13
  • 79
  • 123
2

What is the biggest advantage of using pointers in ObjectiveC

I'd say the biggest advantage is that you can use Objective-C at all - all Objective-C objects are pointers are accessed using pointers (the compiler and the runtime won't let you create objects statically), so you wouldn't get any further without them...

1

Item:

What if I told you to write me a program that would maintain a set of counters, but the number of counters would be entered by the user when he started the program. We code this with an array of integers allocated on the heap.

int *counters = malloc(numOfCounters * sizeof(int));

Malloc works with memory directly, so it by nature returns a pointer. All Objective-C objects are heap-allocated with malloc, so these are always pointers.

Item:

What if I told you to write me a function that read a file, and then ran another function when it was done. However, this other function was unknown and would be added by other people, people I didn't even know.

For this we have the "callback". You'd write a function that looked like this:

int ReadAndCallBack(FILE *fileToRead, int numBytes, int whence, void(*callback)(char *));

That last argument is a pointer to a function. When someone calls the function you've written, they do something like this:

void MyDataFunction(char *dataToProcess);

ReadAndCallBack(myFile, 1024, 0, MyDataFunction);

Item:

Passing a pointer as a function argument is the most common way of returning multiple values from a function. In the Carbon libraries on OSX, almost all of the library functions return an error status, which poses a problem if a library function has to return something useful to the programmer. So you pass the address where you'd like the function to hand information back to you...

int size = 0;
int error = GetFileSize(afilePath,&size);

If the function call returns an error, it is in error, if there was no error, error will probably be zero and size will contain what we need.

iluvcapra
  • 9,436
  • 2
  • 30
  • 32
  • What if I told you that not one lick of this answer was in ObjC? (save heap allocation, of course) – CodaFi Feb 20 '13 at 23:32
  • I admit I never really understood pointers my first few months with Objective-C, and I had to learn plain C in order to actually grok the concept. – iluvcapra Feb 20 '13 at 23:38
-1

The biggest advantage of pointers in Objective-C, or in any language with dynamic allocation, is that your program can handle more items than the names that you invent in your source code.

gnasher729
  • 51,477
  • 5
  • 75
  • 98