pointer to array

#include<iostream>
using namespace std;
int main()
{
int *p,*q,a[]={5,7,8,2};
p=a;
int b[]={3,5,2,4};
q=b;
int e=p-q;
cout<<e;
return 0;
}
// i never understand the line int e=p-q and output of this is 4 so whats is going in this code
Every variable has it's numeric address in memory. (So pointer to a variable is a number).
Local variables in functions are stored in stack. That is every next variable is stored before previous variable.
There is the stack pointer (SP). It points to first stored variable. Memory before this pointer is free.
So let's say in the begin SP = 0x100.

Then we should store variable p. p is pointer.
Size of p usually 8 bytes (amd64).
So address of p will be 0xF8.

Then we should store variable q.
q is pointer.
Size of q usually 8 bytes (amd64).
So address of q will be 0xF0.

Then we should store variable a.
It's array of 4 ints.
Size of every int usually 4 bytes.
So address of a will be 0xE0.
Address if a[0]=0xE0,
address if a[1]=0xE4,
address if a[2]=0xE8,
address if a[3]=0xEC.

Then you say p = a. So value of p is 0xE0.

Then we should store variable b.
It's array of 4 ints.
Size of every int usually 4 bytes.
So address of b will be 0xD0.
Address if b[0]=0xD0,
address if b[1]=0xD4,
address if b[2]=0xD8,
address if b[3]=0xDC.

Then you say q = b. So value of q is 0xD0.

Then you say e = p - q. It means "how many variables of type "p" can be stored (or already stored) between p and q".
It calculated as ([number stored in p] - [number stored in q]) / sizeof(p).
In out example this is (0xE0 - 0xD0) / 4 = 0x10 / 4 = 4.

In read life SP is much bigger and will be some like 0x38CCCC40B0 or so. But results of calculations are the same. p - q = 4.

Understand it?
Last edited on
no
Topic archived. No new replies allowed.