我正在尝试编写一个程序,该程序具有一个获取 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;
}
最佳答案
您现有的代码将值的副本传递给函数,并且该副本会递增,因此原始代码不会改变。
相反,您必须传递指针并重新分配到指针指向的位置。
#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;
}
关于c - 指针有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36022354/