Why can you assign an integer value to an uninitialized pointer

When I do this, it prints "2" perfectly.

int main()
{
    int *p;
    int x = 2;

    *p = x;

    cout << *p;

}

But when I first initialized * p to zero, the program crashes.

int main()
{
    int *p=0;
    int x = 2;

    *p = x;

     cout << *p;

}

I want to ask that the first program even starts successfully first, why can I assign a value to an uninitialized pointer?

[EDIT] My question is really related to this exam question I received. You can mark more than one answer, and it seems that (b) and (c) are both correct. But now I know if work (c) works solely because of luck.

enter image description here

+4
source share
3 answers

undefined. , , , , , undefined.

, , .

+4

, , , - undefined, - . " - .

, , , , , , . p , , , , . , , "0", , , , , , , . , , , , , .

+3

p undefined. , , . , , ++, , SO, , .

int main()
{
    int *p;  //it may even point to the first variable on the main() stack, who knows?...
    int x = 2;

    *p = x;

    cout << *p;

}

, int () 0... , , undefined. 0+4 0-4.... .

!

+1

All Articles