Reputation: 453
How can I substitute one variable a
for another variable b
, in order to change b
?
For example:
NSString *a = @"a";
NSString *b = @"b";
NSString *c = @"c";
a = b;
a = c;
In this case, the value of b
is @"b"
, right? I want to make the value of b
@"c"
, without using b = c
. Probably I should try to understand pointers.
Please make sense of my poor explanation, and give me any advice you can.
Upvotes: 1
Views: 1778
Reputation: 64002
You may be confused because pointers are, frankly, kind of confusing at first. They are variables that hold memory locations. If you have two pointers that hold the same location, and you change the contents of that location using one pointer, then you can see those new contents via the other pointer. It still points to the same location, though.
int x = 10;
// xp is a pointer that has the address of x, whose contents are 10
int * xp = &x;
// yp is a pointer which holds the same address as xp
int * yp = xp;
// *yp, or "contents of the memory address yp holds", is 10
NSLog(@"%i", *yp);
// contents of the memory at x are now 62
x = 62;
// *yp, or "contents of the memory address yp holds", is now 62
NSLog(@"%i", *yp);
// But the address that yp holds has _not_ changed.
Based on your comment, yes, you can do this:
int x = 10;
int y = 62;
// Put the address of x into a pointer
int * xp = &x;
// Change the value stored at that address
*xp = y;
// Value of x is 62
NSLog(@"%i", x);
And you can do the same thing with NSString
s, although I can't think of a good reason for doing so. Change any int
in the example to NSString *
; the int *
becomes NSString **
. Change the assignments and the NSLog()
format specifier as appropriate:
NSString * b = @"b";
NSString * c = @"c";
// Put the address of b into a pointer
NSString ** pb = &b;
// Change the value stored at that address
*pb = c;
// N.B. that this creates a memory leak unless the previous
// value at b is properly released.
// Value at b is @"c"
NSLog(@"%@", b);
Upvotes: 4