Array memory location

In this program, suppose that the array begins with 2000, then the elements must be present in the memory cells arr [1] = 2004 and arr [5] = 2020. and if so, then (ji) should give 16, the difference between memory cells j and i. But it gives a value of "4 for ji. Why does it not give a value of 16?

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

In fact, this indicates a difference in the number of elements.

The difference between the sequential element of the array is always 1 , to find the difference in addresses between them, you need to multiply the difference by sizeof data type

To get the actual address difference,

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

Detailed explanation can be found here.

+10
source

This is of course due to pointer arithmetic

I suggest you read this article Pointer Arithmetic

+2
source

Maybe this 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(); 

}

0
source

All Articles