let's say we have a C function like this,
void assign(int* refs)
{
*refs = 123;
}
and call it in two ways
1.
int a;
assign(&a); // a is assigned a value.
int* a;
assign(a);// runtime error
I know that assign value to pointer that points to null is not ok since there is not correspond memory being allocated.
But
[1] why passing address of uninitialized variable works well?
[2] What does &a
means when a
hasn't been initialized.
The value is uninitialized, but the memory is allocated.Pointer points to memory, not to a value.
It's only a problem to read an uninitialized variable. Taking its address is fine since a variable's address is fixed for its lifetime.
In your first example you have an uninitialized variable of type int
. You take its address (which is valid as above) and pass it to a function which subsequently dereferences that address to write the value of a
.
In the second example, you have an uninitialized variable of type int *
, but then you pass its value to the function. This is not valid because the value of the variable is indeterminate .
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.