【发布时间】: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()中?是的,需要使用您自己的函数(必须更改为采用指针参数)来执行此操作。