Hello! I'm coming from an Objective-C background and am trying to expand my knowledge in C. One thing has me confused, however, and that's the difference between pointers in C and Obj-C. As you can see in the examples below, things seem to behave a bit differently between both languages, and I was wondering if you could help explain why?
C code works fine:
void myFunction()
{
int x, *pointerX;
pointerX = &x;
*pointerX = 5;
// Prints: "x is 5"
printf("x is: %i", x);
}
Obj-C code fails:
- (void)myMethod
{
NSString *string = @"Caramel coffee", *stringPointer;
stringPointer = &string; // Warning: Assignemnt from incompatible pointer type
*stringPointer = @"Chocolate milkshake"; // Exception: Incompatible types in assignment
NSLog(@"string is: %@", string);
}
Question: Why can't I assign stringPointer to the memory address of string (stringPointer = &string;
), and why am I able to perform *pointerX = 5;
under C, but I can't perform *stringPointer = @"Chocolate milkshake";
under Objective-C?
I realize that Obj-C deals with objects and C doesn't, but I can't seem to figure out the behind-the-scenes details as to why it doesn't work in Obj-C. Any help is greatly appreciated. Thanks! :)