简体   繁体   中英

How can I change an int value using function and pointer in 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;
}

I wan't to change the p value to the value that I scanned, what's wrong with my code?

This code demonstrates the right way, and the wrong way to change a number.

The function get_number_A will NOT make a meaningful change to its parameter, because C uses "pass-by-copy" for its parameters.

The function get_number_B will make a meaningful change to its parameter, because a pointer to the variable is passed.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM