I'm reading the solution to a problem in the book Cracking the Coding interview (Q 1.2). The objective there is to implement a function void revers(char* str)
in C that reverses a null terminating string.
The solution code looks something like this:
void reverse(char *str)
{
char* end=str;
char tmp;
if(str)
{
while(*end)
{
end++;
}
end--;
//code to reverse
}
}
Here, str
contains an address right? And if(str)
will only evaluate to false
if str
is 0
, right?
So what I'm saying is, is there no chance that str
will contain the address 0x0000
, thus evaluating if(str)
to false
?
Note: It is still acceptable to assign the value 0 or NULL to a pointer. The nullptr keyword designates a constant rvalue of type decltype(nullptr) . The typedef expression is typedef decltype(nullptr) nullptr_t , of which nullptr_t is a typedef for decltype(nullptr) that is defined in <cstddef> .
"it is possible to assign an integer 0 to a pointer" Yes for object pointers.
Memory address 0 is called the null pointer. Your program is never allowed to look at or store anything into memory address 0, so the null pointer is a way of saying "a pointer to nothing".
The fact you can address 0 (the so called null pointer) is simply a language implementation. It is not pointing to memory address 0. The C++ implementation uses this syntax instead to define a pointer that is pointing to nothing.
str
does indeed contain an address (it's a pointer to char
), and if(str)
will evaluate to false iff the str
is equal to the null pointer.
Note that the null pointer is not required by the standard to refer to address 0
; however, the standard mandates that a literal value of 0
when used in a pointer context must be interpreted by the compiler as the address of the null pointer -- whatever that might be.
This means that the test if(p == 0)
is guaranteed to always be the same as if(p == NULL)
. Also, the conditional if(p)
is guaranteed to always be the same as if(p != 0)
.
Conclusion: your code will always detect a null pointer, but that's not technically the same as a pointer that points to address zero (even though in practice you are going to find that it usually is).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With