为什么这个函数没有在c中递增我的变量?

Vic*_*nce 2 c printing pointers function increment

所以只是在C中试验指针.

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

int main(){
    int x = 0;
    int *p;
    *p = x;
    inc(p);
    printf("x = %i",x);
}
Run Code Online (Sandbox Code Playgroud)

为什么打印"x = 0"而不是"x = 1"?

dbu*_*ush 7

这是你的错误:

*p = x;
Run Code Online (Sandbox Code Playgroud)

你是解除引用p,这是未分配的,并给它当前的值x.所以x不会更改,因为您没有将指针传递x给您的函数,并且取消引用未初始化的指针会调用未定义的行为.

你不是要分配的地址 xp:

p = &x;
Run Code Online (Sandbox Code Playgroud)

或者,您可以p完全删除,只需将地址传递xinc:

inc(&x);
Run Code Online (Sandbox Code Playgroud)