#include <stdio.h>
struct bar
{
int data[10];
};
int main(void) {
printf("%d", ((struct bar*)0)+5);
return 0;
}
Output is 200. I came across this on some c programming website. Can someone explain me this?
#include <stdio.h>
struct bar
{
int data[10];
};
int main(void) {
printf("%d", ((struct bar*)0)+5);
return 0;
}
Output is 200. I came across this on some c programming website. Can someone explain me this?
Edit: I am updating based on the comment section.
We understand that arithmetic on null pointer is undefined behavior. You can read more here.
The current code does not specifically use NULL
. Instead it uses literal 0
which is then casted into null pointer with ((struct bar*)0)
. As a result, in this code we have an undefined behavior, as well. If instead of 0
, we had another literal (say 1
), then whether it produces a value (201
in case of using 1
) or causes an error would be implementation-dependent.
This output (200
) comes from here: sizeof(struct bar)
is 40 bytes and a pointer arithmetic is carried out (5 x 40 = 200
).