0

Like consider I declare two pointers NULL. Then if I compare them, the result is true. But if we consider NULL to be "nothing" then how can we say that two "nothings" are equal? Is that for some specific reason? Any help appreciated. :)

7
  • Because there's only the null pointer. Commented Dec 6, 2016 at 5:53
  • 1
    Consider I declare two ints to be 5. If I compare them, they're equal. The same idea applies to pointers. Commented Dec 6, 2016 at 5:54
  • 3
    "Why" questions are hard to answer on SO. The answer "because the standard says so" is unsatisfying, and the question "why does the standard say that?" requires a psychoanalysis of the personalities and goals of all standards authors, and an understanding of the process by which the standard is produced. Commented Dec 6, 2016 at 5:55
  • Instead, try asking "what" questions that have answers. "What line of the specification defines null pointers to be equal?" is a question that has an answer. "What have members of the standards committee said publically about that design choice?" is a question that has an answer. "What design processes could lead a standards team to produce an "isnan" function for doubles but not an "isnull" function for pointers?" is a question that requires an opinion, but at least it has an answer. Ask a more clear question. Commented Dec 6, 2016 at 5:56
  • @EricLippert : Okay. I got it. New to SO. :) Commented Dec 6, 2016 at 6:08

2 Answers 2

7

In C, two null pointers of any type are guaranteed to compare equal. The macro NULL is defined as an implementation-defined null pointer constant, which in C99 can be portably expressed as the integer value 0 converted implicitly or explicitly to the type void * .

Sign up to request clarification or add additional context in comments.

Comments

2

When you point pointer to NULL then it means that it is pointing to the memory address 0x0.

Consider following example,

#include <stdio.h>

int main()
{
        char *p = NULL;
..
..

Here, *p is pointing to NULL. If we check in gdb then we will get following,

(gdb) p p
$1 = 0x0  

0x0 is the address of NULL value i.e. 0. You cannot access 0x0 memory address.

(gdb) p *p
Cannot access memory at address 0x0

If you try to access memory address 0x0 then program will be crashed by saying segmentation fault

Now if you compare two pointers which are pointing to memory address 0x0 i.e. NULL then it will be same only as the NULL value is 0 by default

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.