designing struct problem

Started by
4 comments, last by Goishin 16 years, 10 months ago
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);

}


Advertisement
Maybe try using a vector?
And push_back() for every player using a for loop.
vector::reserve()
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
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.
Create-ivity - a game development blog Mouseover for more information.
You know, Captain P, you're right. Thanks for catching that.

- Goishin

This topic is closed to new replies.

Advertisement