Sign in to follow this  
Prog101

designing struct problem

Recommended Posts

i have a problem in being able to initalize my array size 1st, what i do is read a text file, which then tells me the number of players there are and i want to pass the number of players to size the array, but i cant give the array a size of the players before i declare the array.
typedef struct sDataType
{
   int id;
   char *name;
}DataType;


DataType gDataType[];
int players =0;

voi init()
{
   txReadFile(text.txt);
   players = txGetNoOfPlayers();
   txgetData(gDataType);

}


Share this post


Link to post
Share on other sites
It takes a little different syntax for declaring an array before you know how big you want it. So you just use a pointer instead.

SomeDataType * blah = new SomeDataType[size];

where:
SomeDataType is the kind of data (int, char, etc.)
blah is the name of your array
size is the name of the variable holding the size of your array (in this case it's the number of players).

You still use the array the same way, you're just declaring it differently. The compiler is choking because when trying to declare an array, it likes to set up all the memory before hand. By doing it via a pointer, like in my example, it tells the compiler that you'll handle that part yourself.

So, looking at your code, we'd probably do something like this:

typedef struct sDataType
{
int id;
char *name;
}DataType;


DataType* gDataType = NULL;
int players =0;

void init()
{
txReadFile(text.txt);
players = txGetNoOfPlayers();
gDataType = new DataType[players];
txgetData(gDataType);
}




Also, you had a typo in your init. You misspelled void.

But you see how I did that with pointers? I declared the pointer and set it to NULL. And then I created the array (with the new command) only AFTER I knew how big I wanted it to be.

Try that out.

- Goishin

Share this post


Link to post
Share on other sites
I'd recommend using a STL container class, such as std::vector or std::deque, rather than using raw arrays. Once you get used to them, they're actually very easy to work with, and they're less likely to cause you trouble.

I'd also recommend using std::string instead of char*. Again, easier and safer to work with. You'd better not use pointers when you don't need them, especially since there are better alternatives for things like these.


@Goishin: You don't need to set your pointer to NULL. You do need to call delete on anything that you called new on, though (and delete[] for anything you new[]'ed). Not doing so results in memory leaks.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this