c - 指针有问题

标签 c pointers

我正在尝试编写一个程序,该程序具有一个获取 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/

相关文章:

当我在函数内打印第一个值后尝试 printf 时出现 C 段错误

c - 使用指针在函数中创建一个新字符串

c - 为什么我从这段代码中得到 "request for member in something not a struct or union"?

Cs50 棕褐色将图像从正常转换为棕褐色的问题

c - 为包装在 C 中的结构中的二维指针数组分配内存

c - 为什么在从文件加载期间起始指针会发生变化?

c - 运行 udev 时挂起

c - 奇偶计数器

c++ - 从数据库中搜索时间复杂度为 O(1)\O(log n) 的行

c - 参数太少错误