Can someone explain, why
int main(void)
{
char *a = NULL;
int *b = NULL;
double *c = NULL;
printf("\n%d %d %d\n%d %d %d\n\n",
(int) (a+1), (int)(b+1), (int)(c+1),
(int) (a+5), (int)(b+7), (int)(c+17));
return 0;
}
outputs
1, 4, 8
5, 28, 136
I think it has something to do with the byte-sizes of those variables. But I don't understand the second line of output.
A null pointer has a reserved value that is called a null pointer constant for indicating that the pointer does not point to any valid object or function. You can use null pointers in the following cases: Initialize pointers. Represent conditions such as the end of a list of unknown length.
A pointer can also be initialized to null using any integer constant expression that evaluates to 0, for example char *a=0; . Such a pointer is a null pointer. It does not point to any object.
Explanation: What happens here is that when a Null pointer is created, it points to null, without any doubt. But the variable of Null pointer takes some memory. Hence when a pointer to a null pointer is created, it points to an actual memory space, which in turn points to null.
In C++11 and beyond, a pointer that is ==NULL will also ==nullptr and vice versa. Uses of NULL other than comparing with a pointer (like using it to represent the nul byte at the end of a string) won't work with nullptr .
If p
is a pointer to type T
, and it holds memory address X
, then p + N
is the memory address X + N * sizeof(T)
.
(int) (a + 1) == 0 + 1 * sizeof(char) == 1 * 1 == 1
(int) (b + 1) == 0 + 1 * sizeof(int) == 1 * 4 == 4
(int) (c + 1) == 0 + 1 * sizeof(double) == 1 * 8 == 8
(int) (a + 5) == 0 + 5 * sizeof(char) == 5 * 1 == 5
(int) (b + 7) == 0 + 7 * sizeof(int) == 7 * 4 == 28
(int) (c + 17) == 0 + 17 * sizeof(double) == 17 * 8 == 136
Minor note: As Barmar points out in his answer, arithmetic on NULL pointers is technically undefined behavior. So a standard-compliant compiler could have done something different with that arithmetic; the code might have printed 1, 3.1415, or a picture of dogs playing poker. But the behavior you observed is the same as the defined behavior you would've observed if you'd started with valid pointers, so you probably don't need to worry about this.
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