0
#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?

Anup Buchke
  • 5,210
  • 5
  • 22
  • 38

1 Answers1

5

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 (201in 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).

Community
  • 1
  • 1
Arash
  • 1,950
  • 14
  • 17
  • Thanks for the answer. The zero typecasting confuses me at times. Can you suggest some material on it? – Anup Buchke Mar 21 '17 at 00:20
  • 1
    See http://en.cppreference.com/w/cpp/types/offsetof for tool to help with similar games without requiring you to dabble in easily-exploding NULL pointers. – user4581301 Mar 21 '17 at 00:25
  • @AnupBuchke. We have a `NULL` pointer of type `struct bar*`. What matters over hear is its size which is the size of the struct. – Arash Mar 21 '17 at 00:32
  • @Arash: You mean a _null pointer_. `NULL` is a macro with a _null pointer constant_, A variable cannot **be** a macro. And there are two reason for undefined behaviour. – too honest for this site Mar 21 '17 at 00:38
  • @Olaf Yes, you are right. I should have said *null pointer*. Thanks for pointing that out. – Arash Mar 21 '17 at 00:48