简体   繁体   中英

Shouldn't dereferencing a pointer provide the value inside the address that you are referencing to?

my code here basically involves a pointer to a 1-D array of 3 integers, I just don't get the output for the line of code 'printf ("Value at address B[0] is: %d\n",*B);'. Like shouldn't dereferencing pointer B provide me the value to the address that it is referencing to? Is there something wrong with my statement? Thanks, the output didn't give me the value instead it provided me the address:'))

#include<stdio.h>
#include<stdlib.h>

int main (void){
    int B[2][3] = {{2,3,4},{5,6,7}};
    int (*p)[3] = B;
    printf("Address at B[0] is: %d or %d\n", B, &B[0]);
    printf ("Value at address B[0] is: %d\n",*B); /*when I dereference pointer B here, shouldn't it give me 
    the value, why is it that when I execute the code, it gives still gives me the address?*/
    printf("B + 1 = %d\n", B+1);
}

上述代码的输出

B is not a pointer. B is an array of two arrays of three int .

When an array is used in an expression, other than as the operand of size of or unary & or as a string literal used to initialize an array, it is automatically converted to a pointer to its first element.

In printf ("Value at address B[0] is: %d\n",*B); , B is automatically converted to a pointer to its first element. So the result of that conversion is &B[0] . Then * dereferences that address. Since &B[0] is the address of B[0] , *&B[0] is B[0] .

Since B is an array of two arrays of three int , B[0] is an array of three int . Since it is an array used in an expression, and is not the operand of sizeof or unary & and is not a string literal used to initialize an array, it is automatically converted to a pointer to its first element. The result of that conversion is &B[0][0] . That is the same address as &B[0] but has a different type.

Then printf ("Value at address B[0] is: %d\n",*B); attempts to print this address. However, %d is for converting int values to decimal numerals, whereas *B produces a pointer, not an int . The behavior of this is not defined by the C standard. Sometimes it will print the address or part of it.

To print addresses, convert them to void * and print them using %p :

printf("Address at B[0] is: %p or %p\n", (void *) B, (void *) &B[0]);
printf ("Value at address B[0] is: %p\n", (void *) *B);
printf("B + 1 = %p\n", (void *) (B+1));

If you print **B , that will show the value of the first element:

  • In **B , B will be converted to a pointer to its first element, &B[0] , yielding **&B[0] .
  • Then *&B[0] reduces to B[0] , yielding *B[0] .
  • Then B[0] is converted to a pointer to its first element, &B[0][0] , yielding *&B[0][0] .
  • Then that reduces to B[0][0] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM