Problem with array of pointers

412
2

Main Question or Discussion Point

Mentor note: Long-time member who hasn't been around for a couple years. This is a problem worth investigating, though, IMO.
There was a problem in an assignment I was solving, which asked me to break up the elements of a linked list into 3 different linked lists. Rather than creating 3 linked lists, I tried to create a general program for any such number and hence used an array of pointers.

A node in my linked list is given as such:

Code:
struct node {
    int data;
    node* next;
};
and i had a function to add elements to it:

Code:
node* getNewNode(int data) {
    node* x = new node;
    if(x == NULL) {
        cout<<"Error: OVERFLOW";
        exit(0);
    }

    x->data = data;
    x->next = NULL;
    return x;
}
   
void addElement(node** start, int data) {
    node* x = getNewNode(data);
    if(*start == NULL) {
        *start = x;
    } else {
        x->next = *start;
        *start = x;
    }
}
and a function to display the list:

Code:
void displayList(node* start) {
    node* x = start;
   
    while(x != NULL) {
        cout<<x->info;
        x = x->next;

        if(x != NULL) {
            cout<<";";
        }
     }
}
and all of this works perfectly fine if i use something like this:

Code:
node* y;
addElement(&y, 21);
addElement(&y, 13);
displayList(y);
But, if i try using an array of pointers, for example:

Code:
node** iList = new node*[2];
node* m = *(iList+0);
addElement(&m, 21);
addElement(&m, 11);
displayList(m);
The output is something like:

Code:
21;11;<random-number>
and then the program segfaults. What am I doing wrong here? For all I know, *(iList+0) is a variable of type node* and hence should satisfy the requirements for it to be the first element in a linked list.. why is it not working?
 
Last edited by a moderator:

Answers and Replies

Related Threads for: Problem with array of pointers

  • Last Post
Replies
2
Views
3K
  • Last Post
Replies
5
Views
1K
  • Last Post
Replies
3
Views
3K
Replies
6
Views
6K
  • Last Post
Replies
3
Views
1K
  • Last Post
Replies
10
Views
3K
  • Last Post
Replies
16
Views
3K
Top