【问题标题】:Problem printing the derefrenced value of a pointer打印指针的取消引用值时出现问题
【发布时间】:2020-12-25 11:06:26
【问题描述】:

我正在尝试理解指针的操作。

以下代码:

void main () {
    int x = 1;
    int y = 2;
    int z = 3;
    
    int *p = &x;
    int *q = &y;
    int *r = &z;

    //print  with labels the values of x, y, z, p, q, r, *p, *q, *r
    printf("x is: %d\n%y is: %d\nz is: %d\n\n",x,y,z);    
    printf("p is: %d\n%q is: %d\nr is: %d\n\n", p, q, r); 
    printf("*p is: %d\n%**q is: %d\n*r is: %d\n\n", *p, *q, *r); 
}

使用 gcc 编译器的结果是:

行的预期结果:

是:

x is: 1
y is: 2
z is: 3

p is: 6422288
q is: 6422284
r is: 6422280

*p is: 00000001
*q is: 00000003
*r is: 76036FED

根据我的理解,这不是最后三行应该出现的结果,它们应该给出与第一个原因相同的值,这个结果背后是否有原因,或者它是否正确并且我遗漏了什么?

【问题讨论】:

  • 第一个\n 之后的每个printf 中都有多余的%

标签: c pointers memory dereference


【解决方案1】:

三个想法:

  1. printf("p is: %d\n%q is: %d\nr is: %d\n\n", p, q, r); 无效。您需要使用%p 来打印指针。

  2. 你所有的 printf 语句都包含太多的百分比字符。

  3. 我同意你的主要观点。假设您删除了多余的百分比字符,您应该会看到 *p is 1, *q is 2, *r is 3

https://repl.it/repls/OpenAngelicControlflowgraph#main.c

【讨论】:

    猜你喜欢
    • 2013-07-04
    • 2015-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多