5

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 we give char* 9 and say that it is a pointer to address 9? Won't we get any error or a warning?

  2. Ok let's say that (char*) 0 is indeed a pointer to character at address 0, but 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 or (char*) 2 etc be?

Edit: Just to put it here whether it helps or not. My initial search for this question occurred when I found out that the last argument in execl linux system call was null and I saw a rather odd looking syntax for it: (char *) 0.

Thanks.

Community
  • 1
  • 1
theprogrammer
  • 1,698
  • 7
  • 28
  • 48
  • 1
    You can define `char *p = (char *)9;` (without warnings), but you can not dereference it, take a look to http://c-faq.com/null/ – David Ranieri Apr 29 '16 at 06:31
  • 1
    It's important to know that a null-pointer doesn't actually have to be a pointer to address `0`, a null-pointer is actually system dependent. *However*, the integer zero when casted to a pointer (any pointer really) is converted by the compiler to the system-dependent null-pointer. – Some programmer dude Apr 29 '16 at 06:32

1 Answers1

18

(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.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765