Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between two pointer variables [duplicate]

i have asked this question in a written test. while running the below code on my lapi, i am getting 10 as output

#include<stdio.h>
int main()
{
  int *i, *j;/* two pointer variable*/
  i = (int *)60;
  j = (int *)20;
  printf("%d \n",i-j);
  return 0;
}

Output :

10 

Can anyone tell me why the output is 10.

like image 442
Sushil Avatar asked Jan 11 '15 10:01

Sushil


2 Answers

According to the C Standard (6.5.6 Additive operators)

9 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.

So your program has undefined behaviour because the pointers do not point to elements of the same array.

Nevertheles it seems that the compiler simply generates an object code for subtracting two pointers irrespective of whether the pointers point to elements of the same array (it trusts you).

In this case the difference between the two pointers according to the pointer arithmetic is the number of elements that can be placed in the memory between two pointers.

In your case the sizeof( int ) is equal to 4. So a memory that has size of 40 bytes can accomodate 10 elements of type int provided that sizeof( int ) is equal to 4.

This value that is 10 is outputed by the printf function.

like image 126
Vlad from Moscow Avatar answered Sep 25 '22 21:09

Vlad from Moscow


You are evaluating the difference, or "distance" between two pointers to int. sizeof(int) is 4 on your platform. The difference between 60 and 20 is 40, which is the distance between 10 ints. Your implementation seems to be simply evaluating this difference.

However, the C standard places a restriction on the evaluation of the difference between two pointers: both pointers must point to elements in an array, or one past the end. If you can ensure both i and j satisfy this, then the difference evaluation is valid. Since your code does not necessarily satisfy that condition, it may have undefined behaviour, in which case the output/outcome could have been anything.

Also note that is is undefined behaviour to de-reference i and j unless they point to valid addresses holding int values.

like image 44
juanchopanza Avatar answered Sep 25 '22 21:09

juanchopanza