cpointersnullchar-pointer

What does (char*) 0 mean?


This is a question in reference to this question: What does (char *)0 mean in C?

There the answers slightly deviated away from explaining what exactly the answer was, but the final answer mentioned that it was a pointer to a character at address 0 and that it was null. This brought up two doubts for me:

  1. In C, can I have char* 9 and say that it is a pointer to address 9? Won't I get an error or a warning?

  2. Let's say that (char*) 0 is indeed a pointer to character at address 0, what does this address 0 mean? I mean how can we say it's a null? In that case what would the value of (char*) 1, (char*) 2, etc. be?


Context: I initially searched for an answer to this question when I figured the last argument in the user-space wrapper execl would be null but instead I saw a rather odd looking syntax for it, i.e., (char *) 0.


Solution

  • (char *) 0 is not a "pointer to a character at address 0". In C (char *) 0 is treated in a special way - it is guaranteed to produce a null-pointer value of type char *. Formally it does not point to any char object. Its actual numerical value (the "address") is implementation-defined and can correspond to any address, not necessarily 0. E.g. numerically (char *) 0 can produce a pointer that "points" to address 0xFFFFFFFF, for one example, if the given platform reserves this address for null-pointer value of char * type. But again, from the language point of view, a null-pointer value does not really point anywhere.

    (char *) 9 does not have such special meaning. The pointer that (char *) 9 produces is also implementation-dependent. In most implementations it will indeed produce a char * pointer to address 9.

    In order to work around that special treatment of (char *) 0 you can try something like

    int i = 0;
    (char *) i;
    

    The above (char *) i (albeit implementation-dependent too) will usually produce a char * pointer to address 0. The key moment here that disables the special treatment is the fact that 0 in the expression is no longer a constant.