문제

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 ?

도움이 되었습니까?

해결책

auto variables (i.e., 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:

  • pointers are initialized to NULL;
  • arithmetic types (integer or floating point) are initialized to 0
  • structs are initialized recursively according to the previous two rules
  • unions have their first named member initialized recursively according to the first two rules

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;

다른 팁

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.

You declare a pointer, but you do not initialize it. It could take on any value, i.e., 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 need to give the p amd temp values - as you have not they can contain anything.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top