-3

I was trying to implement linked list in C++, when this idea struck my mind. With standard node definition as

class node {
public:
    int data;
    node *next;
};

I created an empty list node *head; then tried this

if(head->next == nullptr)
    cout<<"Stores nullptr";
if(! head->next)
    cout<<"Returns bool values";

But there is no output, so what is stored inside head->next ?

Ayxan Haqverdili
  • 17,764
  • 5
  • 27
  • 57
Snigdh
  • 51
  • 11
  • I can't see you do initialization of `next` anywhere, so it will contain a random value. Also the conditions in your `if` statements are equivalent. – πάντα ῥεῖ May 12 '19 at 08:25
  • *I created an empty list* `node *head;` - no, you've created an uninitialized pointer to node class instance. – user7860670 May 12 '19 at 08:29
  • 2
    Possible duplicate of [Implicit cast of null pointer to bool](https://stackoverflow.com/questions/33474487/implicit-cast-of-null-pointer-to-bool) – super May 12 '19 at 08:30
  • To everyone, don't you think c++ automatically does these initializations and create default constructor, I was just exploiting that fact. Now, my question was just what is stored inside `head->next` if head is nullptr(by default)? – Snigdh May 12 '19 at 09:19
  • @Snigdh _"don't you think c++ automatically does these initializations"_ No we don't think so. We **know** that it doesn't. – πάντα ῥεῖ May 12 '19 at 09:23
  • It is atleast mentioned in my book and my compiler does this also. – Snigdh May 12 '19 at 09:44
  • @Snigdh Your book is wrong then or you confused something. – πάντα ῥεῖ May 12 '19 at 09:52
  • @πάνταῥεῖ Ok, so where can I read about this can you provide any reference please. – Snigdh May 12 '19 at 09:54
  • @Snigdh [1](https://stackoverflow.com/questions/1910832/why-arent-pointers-initialized-with-null-by-default) [2](https://stackoverflow.com/questions/26142100/c-default-constructor-does-not-initialize-pointer-to-nullptr) – πάντα ῥεῖ May 12 '19 at 10:00

2 Answers2

0

First of all, you should create some space/allocate memory for the node class in main.

Note that node *head; is only a declaration not a definition. For further details have a look at What is the difference between a definition and a declaration?.

  1. You allocate space for the object
  2. Initialize its values, to be more elegant define a constructor method
    node *head = new node;
    head->next = nullptr;
    head->data=0;

I would still consider this as a duplicate of Linked lists in C++

Croppi
  • 133
  • 8
-1

If you declare node *head;, head is an uninitialized pointer that contains a random address. Dereferencing it is Undefined Behavior?

You need to a) initialize head: node *head = nullptr;, and b) test for that condition: if (head == nullptr) { head = new node; node->head = nullptr; ...

Aganju
  • 5,994
  • 1
  • 9
  • 22