简体   繁体   中英

Pointer points to uninitialized variable

In the following program, ptr points to uninitialized variable x . Before printing ptr , I have assigned 10 to ptr and print it.

#include <stdio.h>

int main()
{
    int *ptr;
    int x;

    ptr = &x;
    *ptr = 10;

    printf(" x = %d\n", x);
    printf(" *ptr = %d\n", *ptr);
}

Both ptr and x print the correct value. But, I have doubt, Is it defined behavior?

Yes, it is. You assign a valid value to ptr and then use indirection to assign a valid value to x .

The address of a variable like x and its value are separate things. After storage is allocated, taking the address is always well defined, regardless of the value in the variable.

Yes , because when you declare x the placeholder / memory will become available for you .

ptr = &x; *ptr = 10; code effectively means

x =10

据我所知,它是定义的行为,因为它没有必要在写入之前初始化内存。

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