This is regarding a small confusion regarding pointers in C++ while comparing them to NULL. Here's the code :
struct node
{
int data;
struct node *left;
struct node *right;
}
int main()
{
struct node *p;
if(p!= NULL)
printf("line1\n");
else
printf("line2\n");
struct node *temp;
if(temp == NULL)
printf("line3\n");
}
The output:
line2
line3
While for the following piece of code:
struct node
{
int data;
struct node *left;
struct node *right;
}
int main()
{
struct node *p;
if(p!= NULL)
printf("line1\n");
else
printf("line2\n");
struct node *temp;
}
This is the output:
line1
Can anyone please explain the reason of such occurrence ?
You declare a pointer, but you do not initialize it. It could take on any value, ie, it is not guaranteed to be NULL
. Of course, it could be NULL
(0), but again, that cannot be counted upon.
The value of an uninitialized variable is indeterminate unless it has static storage duration.
You are reading an uninitialized variable. That is undefined behaviour . Basically, anything can happen. If you turned on your compiler warnings, the compiler would have told you exactly that.
I suspect you believe that your local variables will be initialized automatically. That is not the case. You must initialize them before reading them.
auto
variables (ie, local variables not declared static
) such as p
and temp
are left uninitialized, so their value is indeterminate (essentially, whatever bit string is left in that particular memory cell from a previous operation, which may or may not be a valid value for the given type). Never try to dereference an uninitialized pointer.
Variables declared at file scope (outside of any function block) or with the static
keyword are initialized as follows:
If you change the declaration of p
to
static struct node *p;
then p
would be initialized to NULL. If you don't want to declare p
as static
, then you'll have to initialize it as part of the declaration:
struct node *p = NULL;
您需要给定p
temp
值-因为您没有它们可以包含任何内容。
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.