RE: [ROOT] Dynamic arrays in classes and trees

From: Philippe Canal (pcanal@fnal.gov)
Date: Thu Feb 28 2002 - 00:42:52 MET


Hi Ben,

In the current version a variable size array of pointers (your case) is producing
an error.  

In order to work-around the problem, you can use a flat array that you alias to
the array you actually use.  More specifically I included a new version of your
class.


//Class data.h
#ifndef __data_h
#define __data_h

#include<iostream.h>
#include "TObject.h"
#include "TRandom.h"

class data : public TObject
{
 private:
  Int_t fNwire;
  Int_t fNchan;
  Int_t fArraySize;   // this is 10*fNwire (it could also be fNwire*fNchan).
  Short_t *arrayflat; //[fArraySize]
  Short_t *array[10]; //!this is just for convenience, it is an alias to th
			    // content of arrayflat'

 public:
  data();
  virtual ~data();
  void SetWC(Int_t a, Int_t b) {fNwire=a; fNchan=b; SetArray();}
  void SetArray();
  void Display();

  ClassDef(data,1)
};

#endif
//Class data.C ------------------------------------------------------------
#include "data.h"
ClassImp(data)

data::data()
{
  fNwire=0;
  fNchan=0;
 for(Int_t i=0; i<10; i++)
    {
      array[i]=0;
    }

}

data::~data()
{
  delete [] array;
}

void data::SetArray()
{
 for(Int_t i=0; i<10; i++)
    {
      delete array[i];
    }


  for(Int_t i=0; i<10; i++)
    {
      array[i] = new Short_t[fNwire];
      for(Int_t j=0; j<fNwire; j++)
	{
	  array[i][j] = 4;
	}
    }
}

void data::Display()
{
  cout<<"\n";
  for (Int_t i=0; i<10; i++)
    {
      for(Int_t j=0; j<fNwire; j++)
	{
	  cout<<array[i][j]<<" ";
	}
      cout<<endl;
    }
}



Cheers,
Philippe

PS. In your destructor you had: 'delete [] array;' which did not match the way
the arrays were allocated (i.e. array[i] = new Short_t[];), you need to make
a loop and do 'delete [] array[i];' 



This archive was generated by hypermail 2b29 : Sat Jan 04 2003 - 23:50:43 MET