When is casting void pointer needed in C?

后端 未结 5 1566
没有蜡笔的小新
没有蜡笔的小新 2020-12-05 13:56

I\'ve been looking at Advanced Linux Programming by Mitchell, Oldham and Samuel. I\'ve seen in the section on pthreads something about void pointers and casting tha

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 14:36

    The second example is a good example of why casting to void* is usually a mistake. It should be

    void *primep = ′  // no cast needed
    pthread_join(thread, &primep);
    

    because pthread_join takes a void** as its second argument. The void* only makes sure the bug passes the compiler because the void* is converted to void** automatically.

    So, when do you need to cast to void* or back:

    • when working with pointers stored as integers ((u)intptr_t);
    • when passing pointers to functions that have an incomplete prototype and take void* (or take a different type of pointer and you have void*); that usually means functions taking a variable number of arguments such as printf.

提交回复
热议问题