C pointers vs. Objective-C pointers

前端 未结 7 1560
醉酒成梦
醉酒成梦 2021-02-06 05:37

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 O

7条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-06 05:50

    The thing is that when you create an object, you actually always manipulate it through a pointer assigned to it, hence (NSString *).

    Try doing the same thing in C (working with a string), perhaps it becomes clearer:

    void myFunction()
    {
        char *string = "this is a C string!";
        char **ptr=&string;
    
    
        // Prints: "this is a c string"
        printf("ptr points to %s: \n",  *ptr);
    }
    

    As you can see, pointers work in exactly the same way as they do in objective-c. Bare in mind that there are very few primitives in objective-c (int is the most obvious one). Most of the time you are creating a pointer of type object X (say NSString), and then allocating a chunk of memory (through [[Object alloc] init]) and assigining the start address of that chunk to your pointer. Exactly the same as we've done in C with our string.

提交回复
热议问题