-2

I'm not getting the output. Why it is happening?

#include <stdio.h>
int main(void){
    int a[3][3];
    int *p, *q;
    p=a[0];
    q=a[1];
    printf("%d\n",sizeof(int));
    printf("%d\n",q-p);

    printf("%d %d\n",q,p);
    return 0;
}

Output

4
3
2686728 2686716

I thought (q-p) should be 12! Is my math degrading?!

Anirban Nag 'tintinmj'
  • 5,572
  • 6
  • 39
  • 59
  • Enable compiler warnings, you're assigning `int`s to pointers and doing (integer) arithmetic on 2 unrelated pointers. Also, your array is not initialsed, so `a[0]` and `a[1]` have unspecified values. – Kninnug Sep 22 '14 at 16:08
  • 1
    According to pointer arithmetic this is correct. Check **Differencing**, which is subtraction of two pointers. – ani627 Sep 22 '14 at 16:09
  • @Ani care to explain why? – Anirban Nag 'tintinmj' Sep 22 '14 at 16:10
  • 1
    It shows the difference in units of the base type (`int`). – Some programmer dude Sep 22 '14 at 16:10
  • @juanchopanza: Why `q-p` should be `12`? – ani627 Sep 22 '14 at 16:20
  • It is 12 if you're talking about bytes, but your talking about ints so 3*sizeof(int) is 12. – CleoR Sep 22 '14 at 16:24
  • Maybe I'm just extremely rusty at C, but if the OP did this, p=&a[0] and q=&a[1]. Where multidimensional arrays in c are contiguous by the rows i.e. a[0][0],a[0][1],a[0][2],a[1][0]. Therfore q would be ahead of p by exactly 3 ints. And when doing pointer arithmetic it's going to move the pointer by the base type and this holds p + 3 = q. When doing q - p you get 3. But the OP was expecting it to be 12. Thats because the base units were in ints and not chars. If he did this printf("%d\n",(char*)q-(char*)p); he would get 12 – CleoR Sep 22 '14 at 16:37
  • You can see this when the stack address of the pointers are printed, they are exactly 12 bytes apart or 3*sizeof(int). – CleoR Sep 22 '14 at 16:49

2 Answers2

4

I thought (q-p) should be 12

No. (q-p)==3 shall hold true since they have type int*. Meanwhile it's true that q == p + 3.
Also this is true: (char*)q - (char*)p == 12

starrify
  • 14,307
  • 5
  • 33
  • 50
0

You are getting output value as 3, because both pointers are pointing to integer data type and the difference between them is three objects.

ani627
  • 5,578
  • 8
  • 39
  • 45