-1

这是一个关于指针的基本 C 程序:

#include <stdio.h>

int main() {
    int variable = 20;
    int *pointerToVariable;

    pointerToVariable = &variable;

    printf("Address of variable: %x\n", &variable);
    printf("Address of variable: %x\n", pointerToVariable);
    printf("Address of variable: %x\n", *pointerToVariable); // * is the DEREFERENCING OPERATOR/INDIRECTION OPERATOR in C. 
                                                                //It gives the value stored at the memory address 
                                                                //stored in the variable which is its operand.
    getchar();
    return 0;
}

这会产生以下输出:

Address of variable: 8ffbe4
Address of variable: 8ffbe4
Address of variable: 14

但是*pointerToVariable应该打印 20,不是吗?因为*给出了存储在其操作数中存储的内存地址的实际值,对吧?我错过了什么?

4

3 回答 3

1

首先,

printf("Address of variable: %x\n", &variable);
printf("Address of variable: %x\n", pointerToVariable);

是错误的,因为您使用了错误的格式说明符,导致未定义的行为

要打印地址,您需要

  • 使用%p格式说明符
  • 将相应的参数转换为(void *)

那么,对于

printf("Address of variable: %x\n", *pointerToVariable);

语句,%x格式说明符打印提供的整数值的十六进制表示,因此您在那里得到了正确的输出。

于 2017-03-30T06:17:59.320 回答
1

14是 的HEX20

printf将格式说明符更改为而%d不是作为输出%x20

printf("Address of variable: %d\n", *pointerToVariable);

此外,指针的正确格式说明符是%p,所以

printf("Address of variable: %x\n", pointerToVariable);

一定是

printf("Address of variable: %p\n", (void *)pointerToVariable);
于 2017-03-30T06:19:10.150 回答
1

您的格式是十六进制(base 16)(%x)这一行:

printf("Address of variable: %x\n", *pointerToVariable);//输出:14

如果您想要以 10 为底的输出,那么您需要提供正确的格式:

 printf("Address of variable: %d\n", *pointerToVariable); // output : 20

// 1*16 + 4 = 20

祝你好运

于 2017-03-30T06:27:45.170 回答