如何在C中使用函数和指针更改int值

时间:2018-12-12 14:54:57

标签: c

    int boom_number;
    get_boom_number(boom_number);
    void get_boom_number(int *p)
{
    int x;
    p = &x;
    if(scanf("%d",&x)== 0)
        printf("Input Error!");
    else
        *p = x;
    return;
}

我不会将p值更改为扫描的值,我的代码有什么问题?

1 个答案:

答案 0 :(得分:1)

此代码演示了更改数字的正确方法和错误方法。

函数get_number_A不会对其参数进行有意义的更改,因为C对其参数使用了“ pass-by-copy”。

函数get_number_B将对其参数进行有意义的更改,因为传递了指向变量的指针。

void get_number_A(int x)
{
    x = 5; // This change will NOT happen outside of this function.
}

void get_number_B(int* p)
{
    *p = 7; // This change will happen outside of this function.
}

int main(void)
{
    int number = 0;

    get_number_A(number);
    printf("A.) The number is: %d; it was NOT modified.\n", number);

    get_number_B(&number);
    printf("B.) The number is: %d; it was SUCCESSFULLY modified.\n", number);

    return 0;
}

View this code on IDEOne