function returning a pointer to a nest struct

Hi. I was trying to build a function that takes a numeric array as input and returns the address of a struct representing a pile with the array values "piled up". The code compiles fine, but it does not print the expected result.

I have tried searching the web for "nested structs", "struct pointers", "functions returning struct pointers", but I haven't found anything useful.

Is there a way to fix this program?

The code is this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <iostream>
#include <string>
 
//definition of the struct
struct structure{
    int number;
    structure *next;
};

// definition of the function that should pile up the vector, that is vector[0] is assigned to 
// pile->number, where pile is the output of the function, vector[1] is assigned to
// pile->next->number and so on...
structure* pile_up_vector(int *vector, int vector_size)
{
    int index = 0;
    structure *pile = new structure; //this will be the output
    structure *pile_iterator;
    pile_iterator = pile; // pile_iterator iterates all the nexts and assigns   
                          // the value of number of each struct the value 
                          // vector[i]
    if (vector_size == 0) return 0;
    else
    {
        do
        {
            if(index != 0) pile_iterator = new structure;
            pile_iterator->number = vector[index];
            pile_iterator = pile_iterator->next;
            index = index+1;
        }
        while (index < vector_size);
    }
    return pile; // pointer of the whole struct is returned
}
 
int main()
{
    int vector_size = 3;
    int *vector = new int[vector_size];
    structure *pile;
    int index;
    // initialize vector with 3, 4, 5
    for (index=0; index < vector_size; index++){
        vector[index]=index+3;
    }
    // construction of the pile with the values of vector piled up through pile_up_vector
    pile = pile_up_vector(vector, vector_size);
    // print the values in the structs
    if (pile == 0) std::cout << "null structure" << std::endl;
    else
    {
        for (index = 0; index < vector_size; index++)
        {
            std::cout << pile->number << std::endl;
            if (pile->next == 0) std::cout << "next structure is null" << std::endl;
            else pile = pile->next;
        } 
    }
}


This program prints 3, and then other two random numbers.
Last edited on
You never set the next pointers to point anywhere so the chain is broken already after the first node.
Last edited on
Ok. Now, it works. Thank you very much!!
Topic archived. No new replies allowed.