objective c - Print object pointer address passed by reference -
nsstring *str = @"hello"; nslog(@"pointer = %p", str); [self dosomthingwithstring:&str]; - (void)dosomthingwithstring:(nsstring **)str { *str = @"world"; nslog(@"pointer = %p", *str); }
maybe it's kind of obvious question, expect have same address printed out:
pointer = 0x104ce9f40 pointer = 0x104ce9fa0
no, should not see same address printed, because dosomthingwithstring
assigns new object str
caller. not modify nsstring
in place.
the nsstring
content "hello"
referenced str
no longer referenced after assignment *str = @"world"
, hence different printout.
perhaps better illustration separate string "world"
, this:
nsstring *str = @"hello"; nslog(@"pointer = %p", str); // prints @"hello"'s address ad [self dosomthingwithstring:&str]; - (void)dosomthingwithstring:(nsstring **)str { nslog(@"pointer = %p", *str); // prints @"hello"'s address again nsstring *other = @"world"; nslog(@"pointer = %p", *other); // prints @"world"'s address *str = other; nslog(@"pointer = %p", *str); // prints @"world"'s address again }
Comments
Post a Comment