Reputation: 149
I was purposely trying to get a NULL pointer in C but I failed to do this. Here is what I was coding:
int main(void) {
int x; //UNINITIALIZED so that it will represent "nothing"
int *null_test = &x;
printf("This should be null %p \n", null_test);
}
But it gave me an address: 0x7fd96c300020
which doesnt seem to be NULL
as I was hoping.
Why? I didn't even initializex
but still not null?
Upvotes: 0
Views: 217
Reputation: 50774
After
int *null_test = &x;
null_test
contains the address of x
. This address is independent of the content of x
even if x
has never been initialized.
Upvotes: 9
Reputation: 17668
Why? I didn't even initializex but still not null?
You need to differentiate between 1) definition and 2) initialisation. A variable is defined when the memory is allocated to it. A variable is initialised when that memory location is filled in with some value.
Here x
is uninitialised but already defined - that means being allocated - that means x
has a specific location in memory. And so &x
is not NULL and so null_test
:
int *null_test = &x;
If you want null_test
to be NULL, just assign it explicitly
int *null_test = NULL;
Upvotes: 5