What's the difference between a null pointer and a void pointer?

前端 未结 11 1599
甜味超标
甜味超标 2020-12-02 05:13

Whats the difference between a Null pointer & a Void pointer?

11条回答
  •  無奈伤痛
    2020-12-02 05:42

    A null pointer is guaranteed to not compare equal to a pointer to any object. It's actual value is system dependent and may vary depending on the type. To get a null int pointer you would do

    int* p = 0;
    

    A null pointer will be returned by malloc on failure.

    We can test if a pointer is null, i.e. if malloc or some other function failed simply by testing its boolean value:

    if (p) {
        /* Pointer is not null */
    } else {
        /* Pointer is null */
    }
    

    A void pointer can point to any type and it is up to you to handle how much memory the referenced objects consume for the purpose of dereferencing and pointer arithmetic.

提交回复
热议问题