1

The code is:

char* c;
if(c!=NULL)
{
    cout << "c has an address the address is "<<c;
}
else
{
    cout << "c is null";
}

The output is:

c has an address the address is [Finished in 0.3s]

If c is not NULL, why c doesn't be printed out as an adress something like "0x401dee"

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • 1
    Your program has undefined behaviour. An uninitialized pointer can be null or non-null (or "both" or "neither"), and relying on predictable behaviour when using it is a bad idea. – chris May 09 '15 at 04:22
  • @chris, but if I use "string* s" then it always prints an andress like "0x401dee" –  May 09 '15 at 04:26
  • @lxdthriller, And it doesn't have to; that's undefined behaviour. Next thing you know, the compiler updates and it does something different. Anyway, as explained in the link, `char*` acts differently than other pointers when printing it with well-defined behaviour. – chris May 09 '15 at 04:27
  • @lxdthriller You have an uninitialized pointer. You then attempt to do stuff with it **except** initialize it. Results -- undefined behavior. It doesn't matter if it is a `char *`, a `string* `, an `int *`, or a `Whatever *` -- if it's uninitialized, then reading from or writing to it is undefined behavior. – PaulMcKenzie May 09 '15 at 04:32
  • 1
    This whole undefined behavior thing is a red herring. Yes it's undefined behavior, but that doesn't mean the behavior is completely unpredictable. Compilers are real things whose behavior can be understood, even if that behavior cannot be derived from the language standard. – Benjamin Lindley May 09 '15 at 04:44
  • @PaulMcKenzie Unless that variable is statically-defined, in which case it's a null pointer: http://stackoverflow.com/questions/17012707/initialization-global-and-static-variable-to-0-is-always-unnecessary – Cookyt May 09 '15 at 04:49

1 Answers1

3

The problem with pointers is, that they often have a value after creating it, but its not a NULL pointer (!). But because its a pointer it points to a random address in your memory. That can cause pretty big problems, that's why you should ALWAYS initialize a pointer with

TYPE * NAME = NULL

So it hasn't a value and so it can't point to something, that could cause problems and now you can test with

NAME == NULL

(Of course you can also initialize it with a real value like the address of one of your variables)

LoztInSpace
  • 5,584
  • 1
  • 15
  • 27
Leo Lindhorst
  • 232
  • 1
  • 8