What does having two asterisk ** in Objective-C mean?

后端 未结 5 1041
梦如初夏
梦如初夏 2020-12-03 02:08

I understand having one asterisk * is a pointer, what does having two ** mean?

I stumble upon this from the documentation:

- (NSAppleEventDescriptor          


        
5条回答
  •  半阙折子戏
    2020-12-03 02:31

    Pointer to Pointer

    The definition of "pointer" says that it's a special variable that stores the address of another variable (not the value). That other variable can very well be a pointer. This means that it's perfectly legal for a pointer to be pointing to another pointer.

    Let's suppose we have a pointer p1 that points to yet another pointer p2 that points to a character c. In memory, the three variables can be visualized as :

    So we can see that in memory, pointer p1 holds the address of pointer p2. Pointer p2 holds the address of character c.

    So p2 is pointer to character c, while p1 is pointer to p2. Or we can also say that p2 is a pointer to a pointer to character c.

    Now, in code p2 can be declared as :

    char *p2 = &c;

    But p1 is declared as :

    char **p1 = &p2;

    So we see that p1 is a double pointer (i.e. pointer to a pointer to a character) and hence the two *s in declaration.

    Now,

    • p1 is the address of p2 i.e. 5000
    • *p1 is the value held by p2 i.e. 8000
    • **p1 is the value at 8000 i.e. c I think that should pretty much clear the concept, lets take a small example :

    Source: http://www.thegeekstuff.com/2012/01/advanced-c-pointers/

    For some of its use cases:

    This is usually used to pass a pointer to a function that must be able to change the pointer itself, some of its use cases are:

    • Such as handling errors, it allows the receiving method to control what the pointer is referencing to. See this question
    • For creating an opaque struct i.e. so that others won't be able to allocate space. See this question
    • In case of memory expansion mentioned in the other answers of this question.

    feel free to edit/improve this answer as I am learning:]

提交回复
热议问题