arrays sized at runtime

If you are a new Irrlicht Engine user, and have a newbie-question, this is the forum for you. You may also post general programming questions here.
Post Reply
thespecial1
Posts: 135
Joined: Thu Oct 30, 2008 11:56 am
Location: UK
Contact:

arrays sized at runtime

Post by thespecial1 »

hi guys

i have an array of scene nodes that I use for the menu items

Code: Select all

ISceneNode *menu[5];
however

i am now wanting to read an unkown number of items from sql which isnt a problem the problem is how to set the size of the array to the number of items in the database, with malloc i presume

Code: Select all

ISceneNode **menu;
menu = malloc(5 * sizeof(ISceneNode ));
but i get an error

Code: Select all

Error	14	error C2440: '=' : cannot convert from 'void *' to 'irr::scene::ISceneNode **'

help anyone pweaaaaaase
vitek
Bug Slayer
Posts: 3919
Joined: Mon Jan 16, 2006 10:52 am
Location: Corvallis, OR

Post by vitek »

The C library function malloc() returns a void*. You have to cast the result to the appropriate type to placate the compiler.

That said, you have other problems. You are allocating enough space for 5 scene nodes, but you need to allocate space for 5 scene node pointers. The correct code would be...

Code: Select all

scene::ISceneNode** nodes = 0;
u32 nnodes = 0;

// figure out value for nnodes

nodes = (scene::ISceneNode**)malloc (nnodes * sizeof (scene::ISceneNode*));

for (u32 i = 0; i < nnodes; ++i) {
  nodes [i] = //...
}

// avoid leaking memory
free (nodes);
To eliminate the cast, you could use the C++ new operator.

Code: Select all

scene::ISceneNode** nodes = 0;
u32 nnodes = 0;

// figure out value for nnodes

nodes = new scene::ISceneNode*[nnodes];

for (u32 i = 0; i < nnodes; ++i) {
  nodes [i] = //...
}

// avoid leaking memory
delete [] nodes;
To simplify this greatly, you could just use a core::array<scene::ISceneNode*> or even a std::vector<scene::ISceneNode*>. Both will manage memory allocation and will dynamically resize as is necessary.

Code: Select all

core::array<scene::ISceneNode*> nodes;
u32 nnodes = 0;

// figure out a value for nnodes

for (u32 i = 0; i < nnodes; ++i) {
  nodes.push_back(/*...*/);
}

// no need to deallocate, it is done automatically
Travis
sjb
Posts: 19
Joined: Tue Dec 23, 2008 10:35 pm
Location: Sweden

Post by sjb »

You could also go with either std::list or std::map. (I guess it all comes down to personal preference unless you wanna find every ms of optimization)

Map is pretty nice when you want to find something by key.

like std:map<int,int> someMap;

then you can go:
someMap.insert(make_pair(userid,health));

and when you wanna find the user:
someMap.find(userid);
thespecial1
Posts: 135
Joined: Thu Oct 30, 2008 11:56 am
Location: UK
Contact:

Post by thespecial1 »

thanks that did the trick .. the dream is furthereddddddd ;0)
Post Reply