简体   繁体   English

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

[英]Why is this function not incrementing my variable in c?

So just experimenting with pointers in C. 所以只是在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"? 为什么打印“x = 0”而不是“x = 1”?

Here's your error: 这是你的错误:

*p = x;

You're dereferencing p , which is unassigned, and giving it the current value of x . 你取消引用p ,它是未分配的,并给它当前的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 . 因此, x不会改变,因为你没有一个指针传递x到你的功能,并取消引用未初始化的指针调用未定义的行为

You instead want to assign the address of x to p : 您想要将x地址分配给p

p = &x;

Alternately, you can remove p entirely and just pass the address of x to inc : 或者,您可以完全删除p并将x的地址传递给inc

inc(&x);

Because you don't set p to the address of x 因为您没有将p设置为x的地址

Use 采用

p = &x;

instead of 代替

*p = x;

With *p = x you cause undefined behaviour because p has indeterminate value and points *somewhere*. 使用*p = x会导致未定义的行为,因为p具有不确定的值并且指向*某处*。 But you don't know where it points and with *p = x you write the value of x to that memory location. 但你不知道它在哪里点,与*p = x你写的值x到内存位置。

You need to assign the address of x to p. 您需要将x的地址分配给p。 As mentioned in the other answers you might just want to pass in inc(&x); 如其他答案所述,您可能只想传递inc(&x); . No need to declare a variable and waste it like that. 无需声明变量并将其浪费。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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