-1

This is the program which was asked in an interview to predict the output

  main()
  {
     char **p = 0;
     printf("%d\n", ++p);
  }

Can you please let me know why is the answer 4 here?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Stacky
  • 1
  • 1
  • I hope you critiqued the code for either not including the explicit return type of `int` (required by C99 or C11), or for omitting `return 0;` (basically required for C89 as otherwise the return value from the program is indeterminate, but you're allowed to omit it from the end of `main()` in C99 or C11 and the result is as if you wrote `return 0;`, though IMO it is still best to include it). – Jonathan Leffler Nov 17 '16 at 03:01

2 Answers2

1

A char takes up 1 byte, but the pointer to that char takes up 4 bytes (an int32). So, p is actually a pointer to an int. When you increment a pointer, it moves forward by the amount of bytes of the underlying datatype. So, p moves forward by 4 bytes.

Eric M.
  • 642
  • 5
  • 16
0

The size of a char is one byte, but the size of a pointer (in 32bit code) is four bytes. The double pointer means you're pointing at four byte quantities, thus

p ++

Advances the pointer four bytes (to supposedly the next char *), thus the output of the printf is 4.

woolstar
  • 5,063
  • 20
  • 31