Skip to main content
gamedev.net
🔒 Locked

C++ dynamic array errors

Started by mirirom Nov 24, 2003 at 11:39 PM 2 replies 400+ views
Original Post
mirirom
mirirom
hi, i've tried debugging this to the best of my abilities and i've come up with squat. perhaps one of you experts can shed some light on what's happening in the following code. basically, i have a composite class Foo which contains a dynamic array of types Bar. i'm not sure whether this makes a difference or not but type Bar contains data members of type string. based on the fact that string defines pretty much every overload and enough memory management to hold it's own, i'm under the impression that its inclusion in this example is irrelevant, however... anyway, everything works ok up to the point where i'm trying to re-point Foo's array pointer to the newly created array. here's the code...
class Bar{
private:
  string strCharName; int life;

public:
  //...get n' sets, et al...

};

class Foo{
private:
  Bar *characters; int count, currentSize;

public:
  Bar();
  ~Bar();
  appendChar(const &string, int);
  resizeArray(Bar*);
};

Foo::Bar(){
  count = 0;  currentSize = 2;
  characters = new Bar[currentSize];
}

Foo::~Bar(){
  delete[] characters;
)

Foo::appendChar(const &string s, int i){
  if(count == currentSize)
    resizeArray(characters);
  characters[count++].set(s, i);
}

Foo::resizeArray(Bar* c){
  currentSize+=2;
  Bar* temp = new Bar[currentSize];  //check for fail, blah blah

  for(int i=0; i < count; i++){
    temp[i] = c[i];
  }
  delete[] c;  
  c = temp;    //error is thrown here...at times

}
am i missing something or...? any help, advice, suggestion is greatly appreciated. thanks in advance! ..:: mirirom ::.. [edited by - mirirom on November 24, 2003 12:40:56 AM]
..:: mirirom ::..
Chris Hare
Chris Hare
I didn''t have time to read your full post, but in the last function, your passing the pointer by value, so don''t expect your function to return a new address. The object it points to can be modified, the pointer can''t. Easy mistake to make. Make the pointer a reference, or a return value as well.

Wizza Wuzza?
merlin9x9
merlin9x9
Don''t make your own dynamic arrays. Use std::vector.
mirirom
mirirom
Chris,

/slaps self

OMG OMG OMG.

thanks!!!! i thought for sure i''d be in karmic debt for the hours of ranting profanity (which i passed by reference) to my desktop.

thanks man, that was it
..:: mirirom ::..

Topic Locked

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

Sign in to reply to this topic.