"new" always returns the same pointer

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • YarrOfDoom
    Recognized Expert Top Contributor
    • Aug 2007
    • 1243

    "new" always returns the same pointer

    I have written a class which allocates an array of unsigned chars using new, but when I create multiple instances of this class, they all point to the same block of memory. Any idea what I'm doing wrong here?
    Code:
    //the relevant code in the constructor
    //v is an unsigned char*
    //r and c are integers
    //init is an unsigned char
    this->v = new unsigned char[r*c];
    memset(v,init,r*c);
    Code:
    //the code which creates the objects
    //water,hills and active are all an uninitialised FieldMap
    //gs.rows and gs.cols are integers
    this->water = FieldMap(gs.rows,gs.cols,255);
    this->hills = FieldMap(gs.rows,gs.cols,128);
    this->active = FieldMap(gs.rows,gs.cols,128);
  • YarrOfDoom
    Recognized Expert Top Contributor
    • Aug 2007
    • 1243

    #2
    Fixed it. Stuff like this is what you get when you mix some Java in your C++.

    The change, for those interested:
    Code:
    //the code which creates the objects
    //water,hills and active are all an uninitialised [b]FieldMap*[/b]
    //gs.rows and gs.cols are integers
    this->water = [b]new[/b] FieldMap(gs.rows,gs.cols,255);
    this->hills = [b]new[/b] FieldMap(gs.rows,gs.cols,128);
    this->active = [b]new[/b] FieldMap(gs.rows,gs.cols,128);

    Comment

    • Gashouse60
      New Member
      • Nov 2011
      • 1

      #3
      Just something I would note:
      why aren't you typing the first new -
      //the relevant code in the constructor
      //v is an unsigned char*
      //r and c are integers
      //init is an unsigned char
      this->v = new unsigned char[r*c];
      memset(v,init,r *c);



      instead:
      typedef unsigned char* myOddType;

      main()
      .
      .
      .
      this->v = (myOddType) new myOddType[r*c];
      memset(v,init,r *c);

      Comment

      Working...