Hi all.
This is actually something related to a WINAPI project, but is a basic C++ problem that has caused a glitch. First the code, then the description of the problem...
Code:
//Passing arrays of a structure to a function....
#include <iostream>
using namespace std;
// Structures ________________________________________________________________//
struct My_Struct
{
int x;
int y;
int z;
};
// Prototypes ________________________________________________________________//
void initializer(My_Struct *num_arr, int count);
void ref_adder(My_Struct *structure, int count);
// My_Struct make_array(int count); // Not working.
// Main function _____________________________________________________________//
int main()
{
My_Struct * Test_Struct;
int marker = 0;
while (marker == 0)
{
cout << "Enter an index number (greater than 0) for the array size:_ ";
cin >> marker;
cout << endl;
if (marker == 0)
cout << "Please enter a number greater than 0" << endl << endl;
}
system("cls");
cout << "The index count you set was " << marker <<
". Now here is your dynamic array." << endl << endl;
// Make the dynamic array. I want a function to do this part.
Test_Struct = new (nothrow) My_Struct[marker];
// *Test_Struct = make_array(marker); // Not working very well, at all.
initializer(Test_Struct, marker);
ref_adder(Test_Struct, marker);
int i;
for (i = 0; i < marker; i++)
{
cout << Test_Struct[i].x << " + " << Test_Struct[i].y << " = " <<
Test_Struct[i].z << endl;
}
cout << endl;
system ("pause");
delete [] Test_Struct;
return 0;
}
// Custom functions ___________________________________________________________//
void initializer(My_Struct *num_arr, int count)
{
int i;
for (i = 0; i < count; i++)
{
num_arr[i].x = (i + 1) * 10;
num_arr[i].y = (i + 2) * 10;
}
}
void ref_adder(My_Struct *num_arr, int count)
{
int i;
for (i = 0; i < count; i++)
{
num_arr[i].z = num_arr[i].x + num_arr[i].y;
}
}
/*
My_Struct make_array(int count)
{
return * new (nothrow) My_Struct[count];
}
Not working*/
What I want to do is make the dynamic array inside a function. The code as above (except for the commented out lines) works okay, but is not quite IT. Here's what I am after. Up where the...
Code:
Test_Struct = new (nothrow) My_Struct[marker];
...line appears in the main() function, I want to put a...
Code:
*Test_Struct = make_array(marker);
...line, instead, that returns a dynamic array of struct My_Struct from a function. Something like this one...
Code:
My_Struct make_array(int count)
{
return * new (nothrow) My_Struct[count];
}
I have tried several ways to accomplish this, but none go all the way in doing the job. This one at least compiles, but crashes upon running, when reaching the part that creates the dynamic array (the My_Struct function). I am not doing something right, or what I am trying to do is not possible (though I am pretty sure it must be).
Any help with this? Please?
My sincere thanks in advance for any push in the right direction.