Skip to main content
gamedev.net
🔒 Locked

[C++] array of objects problem

Started by martinuk Mar 27, 2009 at 10:22 AM 7 replies 1.3k views
Original Post
martinuk
martinuk
I have a program use an array of objects,say Banana b[100]; the program runs fine. if I create the banana object array in this way:

Banana b[100];

for(int i =0;i<100;i++)
{
   b.setValue(weight,color);
}

however, when i change to the following way, it has problem.

Banana* b[100];
for(int i =0;i<100;i++)
{
   b = new Banana(weight,color);
}

the b[0] or b[1] object is randomly destroyed for some reason. any idea why?
ToohrVyk
ToohrVyk
What do you mean by "gets randomly destroyed" ? When does it happen, and how do you notice it happens ?
Evil Steve
Evil Steve
How do you know it's randomly destroyed? The code you have there is perfectly fine, it must be some other problem.
martinuk
martinuk
In the real program, I loop through the array list and do some update

for example,
if i initialed all banana weight to 100g
and i loop through then and add 1 to the weight, for 100 times
thereafter all banana->weight should be 200g
but, sometimes later the banana[0]->weight become to 987679886 some random value.

it's a quite large program, here i just use banana[100] as an example.

if both way creating array objects are perfectly fine and with no security issue then, there must be other problems in the rest of my code.
SiCrane
SiCrane
It sounds like you have a buffer overflow or bad pointer error somewhere else in your code, probably accessing the variable or variables immediately before your bananas.
NotAYakk
NotAYakk
Or she is leaving the data on the stack and returning from a function, not realising that the stack then gets overwritten.
martinuk
martinuk
better way doing it


Object** objArr;
objArr = new Object* [100]

maybe?
jpetrie
jpetrie
Quote:

better way doing it


Object** objArr;
objArr = new Object* [100]

maybe?

Not really. There's nothing wrong with the code he posted that would be solved by dynamically allocating the array. The problem is elsewhere.
Zahlman
Zahlman
Show the Banana class.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.