2

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"?

3 Answers 3

7

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);
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.