#include <stdio.h>
int main()
{
int *p = (int*) 60; --- Line 1
int *q = (int*) 40; --- Line 2
printf("%d", p-q); //Output is 5
return 0;
}
Could anybody please explain to me the output of this program?
int **p declares a pointer on the stack which points to pointer(s) on the heap. Each of that pointer(s) point to an integer or array of integers on the heap. This: int **p = new int*[100]; means that you declared a pointer on the stack and initialized it so that it points to an array of 100 pointers on heap.
int *p=&a; is an initialization, not just a "declaration and assignment." There are differences between assignments and initializations; for example, objects with static duration may only be initialized with constants.
They are the same. The first one considers p as a int * type, and the second one considers *p as an int .
int* means a pointer to a variable whose datatype is integer. sizeof(int*) returns the number of bytes used to store a pointer. Since the sizeof operator returns the size of the datatype or the parameter we pass to it.
It means the (implementation-defined) action of assigning an integral value to a pointer happens. This often means that p
points to the memory address at 60
and q
to the address at 40
. These memory addresses could be in virtual memory, hardware memory, and many implementations have different conversion routines for these.
Since this is implementation-defined anything could happen, as described by your implementation.
It's most certainly not, it is used a lot in embedded hardware programming to access certain features or call built-in functions.
Most likely on your system int
is 4 bytes wide, so p - q
equals (60 - 40) / 4 == 5
.
It's making p
point to the memory address 60
and q
point to the memory address 40
. Then presumably your architecture has 4-byte int
s and so p - q
equals 5
((60 - 40) / 4).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With