-4

I was referring to NULL Pointer in What's the difference between a null pointer and a void pointer? According to the post reply by @AnT, "Formally, each specific pointer type (int *, char * etc.) has its own dedicated null-pointer value"

I wrote simple program. But the pointer value is not fixed for integer or character. It changes sometimes. So how can we conclude that NULL pointer to int has a fixed value? Also the value of pointer is never 0.

 #include <stdio.h>

int main()
{
    int a;
    char *ptr; // Declaring a pointer without initializing it
    int *ptrToInt;

    if(ptr)
    {
        printf("Pointer is not NULL\n");
        printf("Value of pointer = %x\n",ptr);
        printf("Value of pointer = %x\n",ptrToInt);
    }
    else
    {
        printf("Pointer is NULL\n"); 
        printf("Value of pointer = %x",ptr);
        printf("Value of pointer = %x\n",ptrToInt);
    }
    return 0;
}
4

1 回答 1

1

NULL is a value that means a pointer of any type is not valid, and void* is a type. In C or C++, the constant 0 can be assigned to a pointer of any type, and will set it to a null pointer of that type. The constant NULL might be declared as 0, ((void*)0), or something else on an unusual system.

A NULL pointer is a pointer, of any type, that’s been set to the invalid value NULL. You have to set it to this value yourself; simply leaving a pointer with no initializer means it might contain garbage. (There are technically a few exceptions, but always initialize your variables.)

A void* is a type that can store any other type of pointer (except a pointer to a function). It can’t be dereferenced, and you can’t index it like an array or do pointer arithmetic on it. It’s typically used as syntactic sugar to let you call a function such as memset(), which just treats the address you give it as an array of bytes to be filled, or assign p = malloc(…), without an explicit cast. In other words, when you just treat a pointer as an untyped block of memory that will be turned into some type of object later, but you don’t care which.

If you want to test the bit values of null pointers of different types, I suggest a cast to uintptr_t and the printf() format specifier in <inttypes.h>. On most but not all implementations, these will all be zero.

于 2015-10-03T17:57:26.590 回答