-1
#include <stdio.h>

int main()
{
    int a[5] = {1,2,3,4,5};
    int *p = a;
    int *q = p++;
    int b = p-q;
    printf("%d", b);
    return 0;
}

p is pointing on the 2 and q is pointing to the 1. I know that Integer takes 4 bytes in the memory, so correct me if I am wrong, but for example if the address of a[0] is 1000, then the address of a[1] will be 1004

if so, why does subtracting these addresses give us 1 and not 4?

H.S.
  • 11,654
  • 2
  • 15
  • 32
HulkStoN
  • 11
  • 3
  • 1
    Because that's how the pointer arithmetic is defined. It's useful so that pointer arithmetic can behave equivalently to array indexing. You should try to look up this topic with a search engine. – Karl Knechtel Dec 21 '21 at 16:31
  • Also, the `int` type *does not*, in C, take up *any specific* amount of memory. It depends on the platform. – Karl Knechtel Dec 21 '21 at 16:31
  • You are incorrect to assume that an integer takes 4 bytes in memory. On many platforms that is true, but not all. – William Pursell Dec 21 '21 at 16:32
  • Note that `*(p+1)` is the same as `p[1]`. What do they have in common? Both know the size of the data type. – Weather Vane Dec 21 '21 at 16:35

2 Answers2

1

Well, you have clearly misunderstood how pointer arithmetic works.

Consider this:

int a[5] = {1,2,3,4,5};
int *p = a;
p = p + 1;

Now where do you expect p to point? At 2, i.e. at a[1]? Or did you expect it to point in the middle of 1, i.e. in the middle of a[0]?

The answer is that p points to a[1].

Now consider

int a[5] = {1,2,3,4,5};
int *p = a;
int *q = a;
p = p + 1;
int b = p-q;

and do some simple substitution:

int b = p-q;

since

p is a + 1
q = a

we get

int b = (a + 1) - a;

which is

int b = 1;

So obviously the result is 1.

Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
0

From C11 Standard#6.5.6p9 [emphasis added]

When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements. The size of the result is implementation-defined, and its type (a signed integer type) is ptrdiff_t defined in the <stddef.h> header. ....

From this:

The subscript which specifies a single element of an array is simply an integer expression in square brackets.

    int a[5] = {1,2,3,4,5};
    int *p = a;
    int *q = p++;

Both pointer p and q pointing to elements of same array object i.e. array a. Pointer p is pointing to second element of array a, which is a[1] (subscript is 1) and pointer q is pointing to first element of array a, which is a[0] (subscript is 0).

The result of p - q is 1 - 0 which is equal to 1. Hence, you are getting output 1.

Ideally, the type of b should be ptrdiff_t and provide %td format specifier to printf() for b:

    ptrdiff_t b = p - q;
    printf("%td", b);
H.S.
  • 11,654
  • 2
  • 15
  • 32