camtorr95
camtorr95

Reputation: 3

Array of linked structs in c++

I want to create an array of linked structs, but I don't know how to populate such array. Here is an example of what I want to do.

struct foo {
    int data;
    foo* next;
};

I want to declare the array inside a loop

while(1) {
    foo array[n];
    // init array, data to -1 and next to NULL;

I'd like to put things inside of it, creating new instances of foo in a way that all foo's linked in index i share a common property.

    foo* new_foo = new foo;
    new_foo -> data = x;
    new_foo -> next = array + i; // index
    array[i] = *new_foo;

    //do things
    iterate(array);

    //delete[] array; maybe
} // end loop, start again with a new array.

The iterate method would be something like this.

for(int i=0; i<n; ++i) {
    foo* iter = array + i;
    while(iter != NULL) {
        //do things
        iter = iter -> next;
    }
}

It doesn't work at all, the iterate method goes on an infinite loop. The error could be somewhere else, but I still don't know if this is the proper way of doing it. I know I have to use delete somewhere too. I'm still new to c++ and I'd love any advice from you. Thanks!

Edit:

This works fine, if anyone wonders.

foo* array[n] = {NULL};

foo* new_foo = new foo;
new_foo -> data = x;
new_foo -> next = array[i];
array[i] = new_foo;

Upvotes: 0

Views: 105

Answers (1)

Chandini
Chandini

Reputation: 550

From what I have understood through your question, You need a way to populate a linked struct and iterate through it. Correct me if I am wrong.

Lets say if u want to populate n structs.

foo* new_foo = new foo;
new_foo -> data = 1;
foo* head = new_foo; // store a starting pointer to the linked list
foo* prev = new_foo;
i=2;
while(i<=n)
{
  foo* new_foo = new foo;
  new_foo -> data = i++;
  prev -> next = new_foo; 
  prev=new_foo;
}
prev->next=NULL;

Now if you u wish to iterate and do things to the populated list.

foo* iter =head;
while(iter!=NULL)
{
  //do things
  iter=iter->next;
}

Now as u want an array of such Linked structs, you can store the head pointers of all the linked structs in an array.

Upvotes: 1

Related Questions