(2 – 4 = -1) when int value assigned to pointer in C?

  • A+
Category:Languages

I am unable to get that why in this program 2 - 4 gives -1, it has assigned int values to pointers rather than addresses, I know but while I compiled it compiler gave some warnings but compiled the program and it executed but...

Program

#include<stdio.h>  int main(void) {      int *p, *q;      int arr[] = {1,2,3,4};      // I know p and q are pointers and address should be assigned to them     // but look at output, why it evaluates (p-q) to -1 while p as 2 and q as 4      p = arr[1];     q = arr[3];      printf("P-Q: %d, P: %d, Q: %d", (p - q), p, q);      return 0; } 

It gives

P-Q: -1, P: 2, Q: 4 

 


Strictly speaking, what happens depends entirely on your compiler and platform... but let's assume we're using a typical compiler and ignoring the warnings.

Let's simplify your question further:

p = 2; q = 4;  printf("P-Q: %d, P: %d, Q: %d", (p - q), p, q); 

which produces the same wacky result:

P-Q: -1, P: 2, Q: 4 

As @gsamaras pointed out, we're trying to subtract two pointers. Let's try and see how this might result in -1:

p - q = (2 - 4) / sizeof(int)       = (-2)    / 4       = -1 

I suggest trying a couple of your own p and q values to see what happens.


Examples with different p and q:

p - q = ?? ========== 0 - 0 =  0 0 - 1 = -1 0 - 2 = -1 0 - 3 = -1 0 - 4 = -1 1 - 0 =  0 1 - 1 =  0 1 - 2 = -1 1 - 3 = -1 1 - 4 = -1 2 - 0 =  0 2 - 1 =  0 2 - 2 =  0 2 - 3 = -1 2 - 4 = -1 3 - 0 =  0 3 - 1 =  0 3 - 2 =  0 3 - 3 =  0 3 - 4 = -1 4 - 0 =  1 4 - 1 =  0 4 - 2 =  0 4 - 3 =  0 4 - 4 =  0 

Generated using gcc -fpermissive on:

#include <stdio.h>  int main() {     printf("p - q = ??/n");     printf("==========/n");      for (int i = 0; i < 5; ++i) {         for (int j = 0; j < 5; ++j) {             int* p = i;             int* q = j;              printf("%d - %d = %2d/n", p, q, (p - q));         }     }      return 0; } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: