Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

nashyo

macrumors 6502
Original poster
Oct 1, 2010
299
0
Bristol
Code:
NSError *error;
NSString *resultString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];

Why the '&' before error?
 
The & means "Take the address of an object".
I give you another example:

Code:
void modify(int *i)
  *i = 10;
}

void test()
{
   int i = 0;
   modify(&i);
}

When you want to modify a local variable that was created on the stack,
you pass in the address of the location of the variable in memory.

This way, the called function can modify the variable (it's memory).
 
The & means "Take the address of an object".
I give you another example:

Code:
void modify(int *i)
  *i = 10;
}

void test()
{
   int i = 0;
   modify(&i);
}

When you want to modify a local variable that was created on the stack,
you pass in the address of the location of the variable in memory.

This way, the called function can modify the variable (it's memory).

I'm confused.
If I want to modify the following pointer (which is pointing at an object)
NSString *string = @"Hello";

I do the following
string = @"Bye";

Why would I need the memory address (&string) of the object?
 
No, you don't.

If you assign a string to an NSString *, you are assigning a pointer to a pointer.
What you do in my example is modifying the memory where the pointer points to.

You are not assigning a new pointer, as with NSString *, you are modifying the underlying memory.
 
No, you don't.

If you assign a string to an NSString *, you are assigning a pointer to a pointer.
What you do in my example is modifying the memory where the pointer points to.

You are not assigning a new pointer, as with NSString *, you are modifying the underlying memory.

ah got ya
thanks
 
Maybe this helps. You might want to assign a pointer to a variable created inside a function:

Code:
void assign_to(NSString **str, NSString *newval)
{
  *str = newval;
}

void blah()
{
   NSString *hello = @"Hello";
   assign_to(&hello, @"Test")
}

If you pass the address, you can modify a local variable (in this case a pointer)
The pointer you pass becomes a pointer to a pointer (note the **).

This way you can modify a localy created pointer.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.