Sahil
Sahil

Reputation: 115

Array memory locations

In this program,Suppose array starts at 2000 ,then elements should be present at memory locations arr[1]=2004 and arr[5]=2020. and if it is so, then (j-i) should give 16, the difference between the memory locations of j and i.But it is giving the value ‘4’ for j-i.Why it is not giving the value 16?

main() 
{
 int arr[]={10,20,30,45,67,56,74};
 int *i,*j; 
 i=&arr[1] ;
 j=&arr[5] ;
 printf ("%d %d",j-i,*j-*i);
} 

Upvotes: 3

Views: 1552

Answers (2)

Muhammad Shujauddin
Muhammad Shujauddin

Reputation: 9

May be it will help you,,

  #include<stdio.h>
  #include<conio.h>
   #include<iostream.h>
   void main ()
      {
        clrscr();
      int arr[4];
     for(int p=1; p<=4; p++)
   {
    cout<<"enter elements"<<endl;
    cin>>arr[p];
           }
    int i,j,k;
 i=arr[2];
j=arr[4];
  k=arr[2]-arr[4];

cout<<k;
  getch();

}

Upvotes: 0

Parimal Raj
Parimal Raj

Reputation: 20565

It is actually telling you the difference in number of element.

The difference between the consecutive element of an array is always 1 to find by address difference between them, you need to multiply the difference with the sizeof the data type

To get the actual address difference ,

int difference =  sizeof(int) * (j - i)

Detailed Explanation can be found Here

Upvotes: 9

Related Questions