Home > OS >  &q - &p, q and p pointing to non-initialised char array. And o/p is 1. How?
&q - &p, q and p pointing to non-initialised char array. And o/p is 1. How?

Time:03-14

main(){
    char a[20],*p,*q;
    p=&a[0];
    q=&a[10];
    printf ("%d\n",&q - &p) }

This C program gives o/p as:

1

As I understand, the values stored at those addresses are garbage. How can their subtraction be 1?

Can anyone please explain how?

CodePudding user response:

q and p are two different pointer variables. They are not two different elements of the same array (of pointers). Therefore &q and &p are two pointers (to pointers) that do not point to elements of the same array (nor one past its end). Therefore evaluating &q - &p causes undefined behavior, and it is not possible to use the language definition to reason about what may or may not happen beyond that point.

See also Is subtraction of pointers not pointing to different elements of same array valid in C?.

What might be happening in your program is that q and p happen to be allocated at adjacent addresses on the stack, with q at a higher address than p, and that the compiler implements &q - &p by subtracting their actual addresses and dividing by their size. That would account for a value of 1. But the compiler is in no way obliged to do this; it could, in principle, instead print 47 or BUG or delete all your files.

Note that what q and p themselves point to is entirely irrelevant; the array a has nothing to do with your code as it stands.

You may have been thinking of doing q-p instead. That would be subtracting pointers to two different elements of the a array. It is perfectly well defined, and the result would be 10.

(By the way, the result of subtracting two pointers has type ptrdiff_t. You are using the printf specifier %x which is only valid for an argument of type unsigned; this causes undefined behavior as well. The correct format specifier would be %td.)

CodePudding user response:

This call

printf ("%x\n",&q - &p);

have undefined behavior because the pointer expressions &p and &q do not point to elements of the same array. That is the expression &p has the type char ** and points to the variable p while the expression &q having the same type char ** points to the variable q.

It seems you mean

printf ("%tx\n",q - p);

In this case the output will be hexadecimal value of 10 a.

Or if you will write

printf ("%#tx\n",q - p);

then the output will be

0xa
  • Related