0
#include <bits/stdc++.h>

using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

void printList(ListNode *head) {
    ListNode *curr = head;
    while (curr != NULL) {
        cout << curr->val;
        curr = curr->next;
    }
}

int main() {
    ListNode *head[5];
    ListNode *node;
    head[0] = new ListNode(1,NULL);
    for (int  i = 1; i < 5; i++) {
        head[i] = new ListNode(i + 1, head[i - 1]);
    }

    node = head[5]; //cannot convert 'ListNode*' to 'ListNode**'
    printList(node);

    return 0;
}

How should i pass last node as single pointer to function ? i am not able to convert node in double pointer to single pointer variable.

Chris
  • 26,361
  • 5
  • 21
  • 42
  • Program compiles [here](https://onlinegdb.com/KWkpIVtQE) if `NULL` is replaced with `nullptr`. – Jason May 20 '22 at 05:08
  • 1
    In C++ arrays start with index 0. `ListNode *head[5];` has 5 elements with index 0,1,2,3,4. In line `node = head[5];`you try to access an element with index 5. Index 5 is out of bounds. The result will be indeterminate. – A M May 20 '22 at 05:40
  • Side note: better to avoid `#include ` - see here: https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h. – wohlstad May 20 '22 at 05:50
  • And shouldn't that be `head` and `node[5]`? A list only has one head but many nodes. You seem to have swapped the two names. – Goswin von Brederlow May 20 '22 at 15:39

1 Answers1

0

Like Armin pointed out in the comments, you are referencing the array beyond the range.

if you replace

node = head[5];

with

node = head[4];  //this is the 5th element of the array.

you would probably get the output you were expecting.

Dr Phil
  • 430
  • 5
  • 17