简体   繁体   中英

Why is this function not incrementing my variable in c?

So just experimenting with pointers in C.

void inc(int *p){
    ++(*p);
}

int main(){
    int x = 0;
    int *p;
    *p = x;
    inc(p);
    printf("x = %i",x);
}

Why is this printing "x = 0" instead of "x = 1"?

Here's your error:

*p = x;

You're dereferencing p , which is unassigned, and giving it the current value of x . So x isn't changed because you didn't pass a pointer to x to your function, and dereferencing an uninitialized pointer invokes undefined behavior .

You instead want to assign the address of x to p :

p = &x;

Alternately, you can remove p entirely and just pass the address of x to inc :

inc(&x);

Because you don't set p to the address of x

Use

p = &x;

instead of

*p = x;

With *p = x you cause undefined behaviour because p has indeterminate value and points *somewhere*. But you don't know where it points and with *p = x you write the value of x to that memory location.

You need to assign the address of x to p. As mentioned in the other answers you might just want to pass in inc(&x); . No need to declare a variable and waste it like that.

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