TArray::Set and changing sizes of arrays

From: George Heintzelman (gah@bnl.gov)
Date: Tue Dec 21 1999 - 18:57:48 MET


It seems that using TArray*::Set(Int_t n), while being able to grow or 
shrink the array, also wipes out any data in the previous array (but 
only if n is >= 0 and not equal to the previous value). This seems 
crazy; if I wanted a new, blank array, I would just create it myself. 
Keeping the old data allows one to easily use TArray's which can grow 
at need.

Currently the code is:

 void TArrayF::Set(Int_t n)
{
   // Set array size of TArrayF object to n floats.
   // If n<0 leave array unchanged.

   if (n < 0) return;
   if (fArray && fN != n) {
      delete [] fArray;
      fArray = 0;
   }
   fN = n;
   if (fN == 0) return;
   if (!fArray) fArray = new Float_t[fN];
   for (Int_t i = 0; i < fN; i++)
      fArray[i] = 0;
}

I propose instead that this code should be:

void TArrayF::Set(Int_t n)
{
   // Set array size of TArrayF object to n floats.
   // If n<0 leave array unchanged.

   if (n < 0) return;
   if (n != fN) {
      Float_t *temp = fArray;
      if (n != 0) {
         fArray = new Float_t[n];
         memcpy(fArray,temp,min(n,fN)*sizeof(Float_t));
      } else {
	fArray = 0;
      }
      fN = n;
      delete [] temp;
   }
}

George Heintzelman
gah@bnl.gov



This archive was generated by hypermail 2b29 : Tue Jan 04 2000 - 00:43:44 MET