【问题标题】:Difference between `*p=&` and `p=&``*p=&` 和 `p=&` 之间的区别
【发布时间】:2017-03-28 21:23:24
【问题描述】:

我收到了这个问题作为练习,但是一旦我到达fp0 = &hundred;,我不知道该怎么做。有人可以帮我吗?

通过 pointex.c 上的代码片段自行解决。会打印什么?

在后面的一些练习中画出代表变量的方框 和代表指针的箭头。

//code fragment g
float ten = 10.0F;
float hundred = 100.0F;
float * fp0 = &ten, * fp1 = &hundred;
fp1 = fp0;
fp0 = &hundred;
*fp1 = *fp0;
printf("ten/hundred = %f\n", ten/hundred);

【问题讨论】:

  • 你在练习之前有没有学习过任何 C 教程?即使这样,问题arrows representing the pointers.中也有提示
  • 是什么阻止了有人真正编译并测试它?为什么它甚至是一个问题?
  • 请注意,* 在声明中表示一件事(变量是指针),在用作解引用运算符时表示另一件事。

标签: c pointers diagram memory-address dereference


【解决方案1】:

让我们从这一行开始:

float * fp0 = &ten, * fp1 = &hundred;

此时,fp0 指向ten 的地址,因此如果像*fp0 那样取消引用,它将返回10.0F。同样*fp1 将返回100.0F。 在这行之后:

fp1 = fp0;

fp1 指向ten 的地址,因为它的值现在是fp0 的值,这只是一个指向存储ten 变量的内存位置的地址。 指针只是地址。取消引用返回指针指向的特定地址中存储的任何值。然后我们有这一行:

fp0 = &hundred;

现在fp0 保存了hundred 变量的地址,因此取消引用它会返回100.00F。下一部分可能有点棘手:

*fp1 = *fp0;

通过取消引用fp1,我们实际上是转到fp1 指向的地址,并用fp0 指向的地址中存储的值覆盖之前存储在那里的值(10.0F)( 100.0F)。因此,输出如下:

printf("ten/hundred = %f\n", ten/hundred);

将是“十/百 = 1.000000,因为我们将 100.0F 除以 100.0F。

【讨论】:

    【解决方案2】:

    逐行解释代码。考虑[] 表示地址。

    float ten = 10.0F;
    float hundred = 100.0F;
    
    float * fp0 = &ten, * fp1 = &hundred;
    
    //fp0 --> [10.0F]
    //fp1 --> [100.0F]
    
    fp1 = fp0;
    
    //fp1 --> [10.0F]
    
    fp0 = &hundred;
    
    //fp0 --> [100.0F] . fp0 get the address of variable hundred. 
    //That means fp0 can change the value stored by variable hundred.
    
    *fp1 = *fp0;  // the value stored at the address `fp1` takes the value stored at the address `fp0`
    
    // [10.0F] --> [100.0F] . Address that was storing 10.0f will now store 100.0f
    // So,  ten = 100.0F and hundred = 100.0F
    
    printf("ten/hundred = %f\n", ten/hundred); //prints 1.00000
    

    【讨论】:

      猜你喜欢
      • 2011-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-27
      • 2011-03-07
      • 1970-01-01
      相关资源
      最近更新 更多