繁体   English   中英

我是否正确理解了代码中指针的使用?

[英]Have I rightly understood the use of pointers in my code?

我不知道我是否 100% 正确,但从我所看到的情况来看,& 运算符的意思是“地址”,即我分配了一个指针的任何变量。 但我看不出指针的使用对我有什么好处。 我的意思是,我想我得到了正确的 output 作为 X = 5.0 和 y = 50.0,但我无法真正看到变量和指针之间的联系。 这是代码:

#include <stdio.h>

int main()
{
    double *x, y;

    printf("Ange x: ", &x); // De-reference to the value of the standard input
    scanf("%lf", x);

    y = *x * 10;

    printf("%.1lf  %.1lf", *x, y);
    return 0;
}

您的代码是错误的,因为x被取消引用而没有分配指向有效缓冲区的指针。

另请注意, &x不是取消引用,而是获取指针变量x的地址。 由于没有格式为"Ange x: "的 output 说明符,因此未使用此地址。

#include <stdio.h>

int main()

{
  double v;
  double *x, y;
  x = &v; // assign a valid address

  printf("Ange x: ", &x); // obtain an address of x (and have it ignore that)
  scanf("%lf", x);

  y = *x * 10;

  printf("%.1lf  %.1lf", *x, y);
  return 0;
}

在您的第一个 printf 中,您使用了 & 并表示您取消引用了 x 指针。 这是错误的,你需要一个 * 来代替。 如果您打印指针的地址,您将不会得到指针所保存的内容,而是它的 memory 地址,可能看起来像“-726529380”,但每次运行它都会改变。

您还需要在您希望打印 x 的第一个 printf 语句中使用“%d”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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