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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With