-2
   #include <stdio.h>
   #include <stdlib.h>

   int main()  
   {   
      int arr[]={10,20,30,40,50,60,70};      
      int *i,*j,*k;     
      k=2686703;     
      i=&arr[1];     
      j=&arr[5];           
      printf("%d\n%d\n",i,j)  ;        
      printf("%d\n",j-i);        
      printf("%d",*(k));  
      return 0;
   }

output :

 2686700  
 2686716  
 garbage value 

why is the difference between j and i =4 and not 16 ? If 4 bytes are reserved for each integer in an array why is their garbage value corrosponding to this intermediate address ?

sumit
  • 87
  • 1
  • 7
  • 1
    please clarify your problem and your sample. For instance, printf("%d\n%d\n",j-i) is wrong as you only have one var to display. I understand that you are trying to understand how pointers to an array work, but the question and the sample are unclear (and the sample contains "absolute" value k=2686703 that can not be used elsewhere – tomsoft Oct 02 '14 at 17:32
  • how can you assign `k=2686703; `? here k is pointer – Rustam Oct 02 '14 at 17:33
  • 1
    The integer type in the format string is also wrong. A pointer subtraction results in a ptrdiff_t value, which may be printed as %td (assuming C99/C11, C89 will need a cast) – doynax Oct 02 '14 at 17:38

1 Answers1

2

why is the difference between j and i =4 and not 16 and if 4 bytes are reserved for each integer in an array

Because this is how pointer arithmetic works: it divides sizeof(element) out of the difference. This simplifies programming with pointers a lot, because it is easier for programmers to think of offsets in terms of array elements, rather than raw bytes.

why is the garbage value corrosponding to this intermediate address

You dereference pointer k, which is assigned a value that is not aligned with any of the integers. Generally speaking, this is undefined behavior. In your case, however, you picked a value that happens to point to the middle of the array. Depending on the system, the result could be anything - from crashing due to an unaligned read to re-interpreting valid bytes as a different integer.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523