I am making an error somewhere at the last line. It is not showing the correct value at the address.

   /* an array with 5 elements */
   double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
   double backup[5];
   double *p;
   double address;

   int i = 0;

   memcpy(&backup, &balance, sizeof(balance));
   p = backup;

   /* output each array element's value */
   printf( "Array values using pointer\n");
   for ( i = 0; i < 5; i++ )
   {
       //printf("*(p + %d) : %f\n",  i, *(p + i) );
       printf("&p[%d] : %f\n",  i,  p[i]);
       printf("&p[%d] : address: %p\n",  i,  (void*)(&p+i));
   }

   int offset = 4;
   printf("Contents of &p[%d] : address: %x is %f\n",  offset,  ((&p)+(offset)), p[offset]);
   double* newPointer;
   newPointer = ((&p)+(offset));
   printf("The content again: %f at address: %x\n",  *(newPointer), newPointer);

// output is incorrect

The content again: 0.000000 at address: 28feec

有帮助吗?

解决方案 2

memcpy(backup, balance, sizeof(balance));
p = backup;

printf( "Array values using pointer\n");
for ( i = 0; i < 5; i++ ){
    //printf("*(p + %d) : %f\n",  i, *(p + i) );
    printf("p[%d] : %f\n",  i,  p[i]);
    printf("p[%d] : address: %p\n",  i,  (void*)(p+i));
}

int offset = 4;
printf("Contents of p[%d] : address: %p is %f\n",  offset,  p+offset, p[offset]);
double* newPointer;
newPointer = p+offset;
printf("The content again: %f at address: %p\n",  *newPointer, newPointer);

其他提示

Just from the typing I'd say, this:

newPointer = ((&p)+(offset));

should be:

newPointer = p + offset;

This:

((&p)+(offset))

returns a double **, as you take the address of a double *. Adding to this any offset still leaves it a double **. This you surely would not like to assign to a double *.

I am making an error somewhere at the last line

This mistake of taking the address of p is also made at several other location before "the last line".


And to point this out again:

To print out a pointer's value cast it to void * (if it isn't one already) and use the p conversion specifier:

printf("The content again: %f at address: %p\n",  *newPointer, (void *) newPointer);

Using x or d or i offers you a fair chance to lose half of the address' significant bits.

double *p; Here p itself is a address locating pointer p. So while adding an offset just do, p + offset

Here is an diagrammatic representation how pointer behaves. p is a pointer pointing/holding address of backup. So p has address 0x2000 but &p is address of p which is 0x3000. Therefore &p + offset leads to different memory location which is happening in your case.

   p                  backup              
+------+             +------+          
|      |             |      |                        
|0x2000|------------>|0x1000| 
|      |             |      |
+------+             +------+
 0x3000               0x2000 

Also use,

%p format specifier for pointer addresses.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top