Void ** a generic pointer?

前端 未结 3 1538
北海茫月
北海茫月 2020-12-05 18:11

void * is a generic pointer, but what about void **? Is void ** also a generic pointer?

Can we typecast void ** t

相关标签:
3条回答
  • 2020-12-05 18:54

    Void ** a generic pointer?

    void ** is not a generic pointer. Standard says only about void * to be a generic pointer.

    Chapter 22: Pointers to Pointers:

    One side point about pointers to pointers and memory allocation: although the void * type, as returned by malloc, is a generic pointer, suitable for assigning to or from pointers of any type, the hypothetical type void ** is not a generic pointer to pointer.


    Can we typecast void ** to int **, char ** and so on.

    No. You should not.

    C-FAQ says that:

    There is no generic pointer-to-pointer type in C. void * acts as a generic pointer only because conversions (if necessary) are applied automatically when other pointer types are assigned to and from void *'s; these conversions cannot be performed if an attempt is made to indirect upon a void ** value which points at a pointer type other than void *. When you make use of a void ** pointer value (for instance, when you use the * operator to access the void * value to which the void ** points), the compiler has no way of knowing whether that void * value was once converted from some other pointer type. It must assume that it is nothing more than a void *; it cannot perform any implicit conversions.

    In other words, any void ** value you play with must be the address of an actual void * value somewhere; casts like (void **)&dp, though they may shut the compiler up, are nonportable (and may not even do what you want; see also question 13.9). If the pointer that the void ** points to is not a void *, and if it has a different size or representation than a void *, then the compiler isn't going to be able to access it correctly.

    0 讨论(0)
  • 2020-12-05 19:09

    No. void** is a pointer to void*, and nothing else. Only void* acts like a generic pointer.

    Note that actually trying it will probably yield consistent results, but only the above is mandated by the Standard, anything else is Undefined Behaviour and may crash without mercy.

    0 讨论(0)
  • 2020-12-05 19:14

    void** is a pointer to void*. On top of it being undefined behavior (which while scary, the behavior is often in effect defined by your compiler), it is also a huge problem if you do the reinterpret_cast:

    int x = 3;
    char c = 2;
    int* y = &x;
    void* c_v = &c; // perfectly safe and well defined
    void** z = reinterpret_cast<void**>(&y); // danger danger will robinson
    
    *z = c_v; // note, no cast on this line
    *y = 2; // undefined behavior, probably trashes the stack
    

    Pointers to pointers are very different beasts than pointers. Type changes that are relatively safe on pointers are not safe on pointers to pointers.

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