【问题标题】:Having issue with pointers [duplicate]指针有问题[重复]
【发布时间】:2016-07-01 13:06:53
【问题描述】:

我正在尝试制作一个程序,该程序具有获取 int 并使用指针将 int 增加 1 的函数。

这是我试图做的,但它不起作用......

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

void inc(int x);

int main()
{
    int x = 0;

    printf("Please enter a number : ");
    scanf("%d", &x);

    printf("The value of 'x' before the function is - '%d'\n", x);
    inc(x);
    printf("The value of 'x' after the function is - '%d'\n", x);

    system("PAUSE");
    return 0;
}

void inc(int x)
{
    int* px = &x;
    *px = x + 1;
}

【问题讨论】:

  • C11 标准草案,6.5.2.2 Function calls, Section 4 An argument may be an expression of any complete object type. In preparing for the call to a function, the arguments are evaluated, and each parameter is assigned the value of the corresponding argument. 93)A function may change the values of its parameters, but these changes cannot affect the values of the arguments.[...]
  • 您需要使用指针将参数传递给 inc。 tutorialspoint.com/cprogramming/…
  • 请注意您如何将 x 按地址传递给 scanf 以读取值并将其存储在 your 变量中的 main() 中?是的,需要使用您自己的函数(必须更改为采用指针参数)来执行此操作。

标签: c pointers


【解决方案1】:

您现有的代码将值的副本传递给函数,并且该副本递增,因此原始代码保持不变。

相反,您必须传递指针并重新分配指针指向的位置。

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

void inc(int *x);

int main()
{
    int x = 0;

    printf("Please enter a number : ");
    scanf("%d", &x);

    printf("The value of 'x' before the function is - '%d'\n", x);
    inc(&x);
    printf("The value of 'x' after the function is - '%d'\n", x);

    return 0;
}

void inc(int *x)
{
    *x = *x+1;
}

【讨论】:

  • 谢谢,你能解释一下为什么你在函数中输入了'&x'而不是它的值吗?
  • 我们正在尝试更改该值,因此我们必须传递存储它的地址并写入该地址。
猜你喜欢
  • 2012-10-14
  • 2019-03-11
  • 2014-06-26
  • 2012-05-14
  • 2017-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多