1

为了改变,我怎样才能用一个变量替换a另一个变量?bb

例如:

NSString *a = @"a";
NSString *b = @"b";
NSString *c = @"c";

a = b;
a = c;

在这种情况下, 的值为b@"b"对吗?我想制作 的值b @"c",而不使用b = c。可能我应该尝试理解指针。

请理解我糟糕的解释,并给我任何建议。

4

1 回答 1

4

您可能会感到困惑,因为坦率地说,指针起初有点令人困惑。它们是保存内存位置的变量。如果您有两个持有相同位置的指针,并且您使用一个指针更改该位置的内容,那么您可以通过另一个指针查看这些新内容。不过,它仍然指向同一个位置。

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.

根据您的评论,是的,您可以这样做:

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);

你可以用NSStrings 做同样的事情,尽管我想不出这样做的充分理由。int将示例中的any 更改为NSString *; int *变成NSString **. _ 根据需要更改分配和NSLog()格式说明符:

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);
于 2013-02-28T21:30:18.493 回答