0

Assume that float takes 4 bytes, predict the output of following program.

#include <stdio.h>
 
int main()
{
    float arr[5] = {12.5, 10.0, 13.5, 90.5, 0.5};
    float *ptr1 = &arr[0];
    float *ptr2 = ptr1 + 3;
 
    printf("%f ", *ptr2);
    printf("%d", ptr2 - ptr1);
 
   return 0;
}

My query is, I am not getting why the output for 2nd printf statement is 3 and not 12?

Any help in this regard will be highly appreciated.

rici
  • 234,347
  • 28
  • 237
  • 341
chaaru
  • 25
  • 3
  • 3
    Why would it be anything else? It's effectively equivalent to `x + 3 - x` – Shawn Jul 20 '22 at 04:39
  • 2
    Note that adding an integer to a pointer actually adds that many _units_. `x + 3` will increase `x` by `3 * typeof(float)`. Similarly, subtracting two pointers results in the number of _units_ by which they differ. Otherwise `arr[1]` would not be very useful. `arr[1]` is equivalent to `*(arr + 1)`, which would be garbage if the resultant pointer is only changed by one byte; it needs to be changed by one _unit_ (i.e. 4 bytes further, if dealing with 4-byte floats). – Amadan Jul 20 '22 at 04:43
  • This homework assignment tries to make sure you understand "pointer arithmetic". On a side note: in the `printf`, you should not use "%d" for that. I leave it up to you (as part of your homework) to look up the correct formatting symbols to use. – BitTickler Jul 20 '22 at 04:45
  • Unrelated, `ptr2 - ptr1` is a `ptrdiff_t` result, and should use `%td` for the `printf` format specifier. – WhozCraig Jul 20 '22 at 04:46
  • You can get 12 if you try explicit conversion to regular numerical values: `printf("%ld", (long) ptr2 - (long) ptr1);` (no real point in doing that, though. This is for demo purposes only) – qrsngky Jul 20 '22 at 04:46

0 Answers0