-
Dynamic arrays
Hi Guys!
I'm back....
I am currently going through some code in class. I have a problem, I want to make the gather() and show() progs dynamic. But it won't let me, my teacher says to use pointers but I can't get them to work. Its basicly everytime MAX is used, I get an error telling me that it expects a const. Using MSVC++ at course, Bloodshed 5 at home.
Code:
#include <iostream.h>
#define LENGTH 20
#define TAB '\t'
//#define MAX 9 //Nine Planets
int MAX = 9;
int *pMax;
struct planet {
char name[LENGTH];
int howfar;
};
struct planet Gather(void); // structure as output
void Show(struct planet p[MAX]); // structure as input
main()
{
pMax = &MAX;
int i;
cout << "How Many Planets Would You Like? ";
cin >> MAX; //Gather the information for how many planets to be placed in database
struct planet solarsystem[MAX];
for (i=0; i<MAX; i++)
{
solarsystem[i] = Gather(); // get details for each planet and store
}
cout << endl << "Planet Name" << TAB << "Distance from Sun";
Show(solarsystem); // display the details
return(0);
}
struct planet Gather(void)
{
struct planet temp;
cout << "ENTER THE PLANET NAME ";
cin >> temp.name;
cout << "ENTER THE PLANET DISTANCE ";
cin >> temp.howfar;
return(temp);
}
void Show(struct planet p[MAX])
{
int x;
for (x = 0; x<MAX; x++)
{
cout << endl << p[x].name << TAB << TAB;
cout << p[x].howfar << endl;
}
}
Thankyou for any help!
-
Try change
to
An (static)array declaration requires that a constant expression is specified. The size of the array must be determined at compile time and not run-time.
Consider situation
Code:
...
cin >> MAX;
int Int = new int[MAX];
//Problem arises
//Size not determined at compile time
...
If you want to declare a dynamic array you will do it trough a pointer
Code:
...
cin >> MAX;
//Now it is possible
int *pInt = new int[MAX];
...
-
Instead of struct planet solarsystem[MAX]; in order to make the array dynamic, type planet *solarsystem=new planet[MAX]; In the rest of the program, use the arrow(->) operator instead of the dot(.) operator for indirection. In this case, MAX need not be declared as a constant. The value of MAX can now be input by the user, or generated within the program.
Compiler:Turbo C++ v3.01