What is ** in C++?

后端 未结 11 1258
野性不改
野性不改 2020-12-04 14:24

I\'ve seen some code, as well as some errors generated from my compiler that have a \'**\' token before the variable (eg **variablename unreferenced-- or someth

相关标签:
11条回答
  • 2020-12-04 14:52

    ** is not actually only pointer to pointer (as in declaration), but is also the dereference of a dereference (in a statement).

    It is used often in C which does not have the & notation for references, e.g. to update a return value which is a pointer type:

    int alloc_foo(struct foo **foo_ret)
    {
        *foo_ret = malloc(sizeof(struct foo));
        return 1; /* to indicate success; return value in foo_ret */
    }
    
    0 讨论(0)
  • 2020-12-04 14:52

    You can interpret it literally -- pointer to a pointer

    0 讨论(0)
  • 2020-12-04 14:53

    I just wanted to underscore some of the uses for a pointer to a pointer. Most of these are touched on by other posts, but I thought reiteration might help.

    • It allows a callee to modify a pointer owned by the caller. For example, one could pass a pointer to a pointer to the beginning of a string, and the callee could modify the pointed-to pointer to now point to a position within the string where a particular character occurs.

    • Because arrays degrade to pointers (and pointers can be treated as arrays), you will often see a pointer to a pointer if you have:

      • A pointer to an array. This is a generalization of the above case, since a "string" (a C-style string, anyway) is really just an array of chars.

      • An array of pointers. You might, for example, have an array of pointers to objects, allowing for polymorphism, or an array of pointers to select objects stored in another collection.

      • An array of arrays. Again, arrays degrade to pointers, so this is a specific case of the above. This is often used for so called "jagged" arrays (as opposed to rectangular).

    0 讨论(0)
  • 2020-12-04 14:59

    One common use is that it allows a function to set the pointer to null.
    So free(pointer) frees up the memory allocated to pointer but leaves the pointer dangerously pointing at the free memory.
    Instead declare a my_free(**pointer) and call my_free(&pointer) so my_free() can set the pointer to null after freeing it.

    0 讨论(0)
  • 2020-12-04 14:59

    It's one of the allures of C++ Sigils. From my own personal experience, I can vouch faster and more efficient read-access performance using dereference operators on STL's Arrays & Vectors. I've also adopted habitual shared pointer methods if you're curious. :)

    0 讨论(0)
  • 2020-12-04 15:00

    ** is a pointer to a pointer.

    It might be a matrix (an array of arrays) or an array of strings (a char array), etc.

    0 讨论(0)
提交回复
热议问题