0

In the following code:

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
int main()
{

   double *p= (double *)malloc(sizeof(double)*5);
   double *s= (double *)malloc(sizeof(double));

   printf("Enter first value: "); scanf("%lf",p);
   printf("\nEnter 2nd value: "); scanf("%lf",p+1);
   printf("\nEnter 3rd value: "); scanf("%lf",p+2);

   printf("\n\ntable is:\n");
   printf("1st value %f\taddress: %p\n",*p,p);
   printf("2nd value %f\taddress: %p\n",*(p+1),(p+1));
   printf("3rd value %f\taddress: %p\n",*(p+2),(p+2));
   printf("\n\n\nvalue %f\taddress: %p\n",*s,s);

return 0;}

Now suppose that the pointer p contains the hex value 00BD0D50. But the address obtained from when i use p+1 , will give the hex value. 00BD0D58. Why there is this gap of 00000008 between these values even when only 1 is added to p's value ?

I tried using %d in place of %p to output pointer's value but still it had a difference of 8.

And if there is some reason behind it, is there any other way to access a value at address lying between this gap of 00000008 bytes? ( for example in above case, is there any way to access value at 00BD0D51 ?)

Lincoln
  • 165
  • 1
  • 11

2 Answers2

0

Why there is this gap of 00000008 between these values even when only 1 is added to p's value ?

Because size of double type is 8 bytes presumably on your machine. That is called pointer arithmetic. So when you add 1 to the pointer, in reality 8 bytes are added to it due to size of pointee.

is there any other way to access a value at address lying between this gap of 00000008 bytes?

Yes you need to cast the pointer say to char * before doing the pointer arithmetic.

PS. Also you have undefined behaviour when trying to print value of *s - because it has not been initialized.

Also when using %p format specifier you need to cast the pointer to void* in printf, e.g.

 printf("1st value %f\taddress: %p\n",*p, (void*) p);
gmoniava
  • 18,228
  • 5
  • 33
  • 74
0

This is pointer arithmetic! p+1 is the address of the next double in memory. As your doubles are 8 bytes long, so is p+1.

Jean-Baptiste Yunès
  • 30,872
  • 2
  • 40
  • 66