Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Problem with array of pointers

  1. Apr 25, 2008 #1
    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 (Text):

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

    Code (Text):

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

        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 (Text):

    void displayList(node* start) {
        node* x = start;
        while(x != NULL) {
            x = x->next;

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

    Code (Text):

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

    Code (Text):

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

    Code (Text):

    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?
  2. jcsd
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Can you offer guidance or do you also need help?
Draft saved Draft deleted