What is a void pointer and what is a null pointer?

后端 未结 9 645
無奈伤痛
無奈伤痛 2020-11-29 00:32

So I was going through some interview questions and I came across one about void and null pointers, which claims:

a pointer with no return type is cal

9条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-29 00:52

    The two concepts are orthogonal:

    1. A void pointer, (void *) is a raw pointer to some memory location.
    2. A null pointer is a special pointer that doesn't point to anything, by definition. It can be a pointer to any type, void or otherwise.

    A void pointer can be null or not:

    void *void_ptr1 = nullptr;
    void *void_ptr2 = malloc(42);
    void *void_ptr3 = new Foo;               // void * can point to almost anything
    void *void_ptr4 = (char*)void_ptr3 + 1;  // even somewhere inside an object
    

    A non-void pointer can also be null or not:

    Foo *f = nullptr;
    Foo *g = new Foo;
    

提交回复
热议问题