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.
#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 = newint[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.