Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 402
theprogrammer Avatar asked Apr 29 '16 06:04

theprogrammer


1 Answers

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

like image 105
AnT Avatar answered Oct 04 '22 21:10

AnT