slboat
slboat

Reputation: 532

pass a pointer value in objective-c

i just learn the objc language,so my question is kind stupid,but still i very curiosity,I want pass a objc instance pointer to another variants,so i can do this in the C

char *astr = malloc(sizeof(char) * 90);
void *copystr = astr;
sprintf(astr, "hello %s", "me");
// insert code here...
NSLog(@"|%s| copy to |%s|", astr, copystr);

but in objc,it's not work in any way.

NSString *conststr = @"ha!damn!dead!";

//if we pass the pointer to anoter
id *otherSpaceStr = conststr; //this is noway to work
void thirdSpaceStr = conststr; //void won't work too

so my question is after all,them all are pointer,why can't pass them. enter image description here enter image description here

i look into the debug windows,found them not only pointer,them seems have type too enter image description here

Upvotes: 0

Views: 81

Answers (1)

Brian Tracy
Brian Tracy

Reputation: 6831

Thats because id is already a pointer. From the Apple Documentation.

typedef struct objc_object *id;

As you can see, id means "a pointer to any type". This means that when you assign your NSString to otherSpaceStr (previously id *), you are assigning it to a pointer to a pointer.

 NSString *conststr = @"ha!damn!dead!";     // pointer to NSString
 id otherSpaceStr = conststr;               // pointer to anything

So just remember, id is already a pointer, and there is no need for two levels of indirection (id *).

Upvotes: 1

Related Questions