Suraj Menon
Suraj Menon

Reputation: 1604

Ambiguity in address difference in an Array

#include <stdio.h>
main()
{
    int a[] ={ 1,2,3,4,5,6,7};
    char c[] = {' a','x','h','o','k'};
    printf("%d ", (&a[3]-&a[0]));
}

The output of the program is 3. However , the difference in the outputs of values obtained below is 12.Can someone please explain the ambiguity.

#include <stdio.h>
main()
{
    int a[] ={ 1,2,3,4,5,6,7};
    char c[] = {' a','x','h','o','k'};
    printf("%d     %d ", &a[3],&a[0]);
}

Upvotes: 1

Views: 144

Answers (4)

Alok Singhal
Alok Singhal

Reputation: 96211

First of all, a[i] is automatically translated to *(a+i) by the compiler (see https://stackoverflow.com/a/1995156/226621 for an interesting consequence of this). So, &a[i] is the same as &*(a+i), or a+i. This means that:

&a[3]-&a[0]

is the same as

(a+3) - (a+0)

which is 3. This also means that for p and q, both of which are pointers to some type T (i.e., *p and *q are of type T), and when p-q is valid, it gives you the number of elements of type T between p and q. The compiler will automatically convert the difference in values of p and q and divide that difference by sizeof(T) to give you the correct number.

Therefore, when you print the individual pointer values, and then subtract those values yourself (in your head for example), you will get a number that is sizeof(T) times "too big".

On your machine, 12 / sizeof(int) == 3, which means that sizeof(int) is 4.

Incidentally, to print pointer values, you should use %p specifier:

printf("%p %p\n", (void *)&a[3], (void *)&a[0]);

Upvotes: 0

SomeWittyUsername
SomeWittyUsername

Reputation: 18368

In the first case the operator '-' is applied to a pointer and the result is measured in number of elements rather than in absolute addresses. Check out this: Pointer Arithmetic .

Upvotes: 1

MByD
MByD

Reputation: 137402

This is called pointer arithmetics. The result is the values divided by sizeof(int)

If the difference in bytes is 12, and the size of int is 4, than the result is 12/4=3

BTW, when printing addresses use the format specifier %p:

printf("%p     %p ", &a[3],&a[0]);

Upvotes: 2

NullPoiиteя
NullPoiиteя

Reputation: 57322

you are printing the address

#include<stdio.h>
main()
{
 int a[] ={ 1,2,3,4,5,6,7};
char c[] = {' a','x','h','o','k'};
printf("%d     %d ", &a[3],&a[0]);

}

result

-1085768040     -1085768052 

codepad

and for first one Binyamin Sharet answer is perfect

Upvotes: 0

Related Questions