Saving an array of histograms

I thought this could be easily done with an for loop. But i don’t get it working.

[code]TH1D *h[24]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

//some code for filling the histograms

for(Int_t i=1;i<25;++i) {
Int_t createoutputfile = sprintf(outputfile,“output_%02u_%s.root”,i,detectorname);
TFile testfile(outputfile,“recreate”);
h[i]->Write();
}[/code]

I get this errormessage:
Error: illegal pointer to class object h[i] 0x0 986 histo.C:170:
*** Interpreter error recovered ***

The line with h[i]->Write(); is line number 151 and the document ends at linenumber 154.

Hi,

I think that instead of for(Int_t i=1;i<25;++i)
you meantfor(Int_t i=0;i<24;++i)
(C++ array indices are from 0 to len-1).

Cheers,
Philippe.

Thanks, but it only works for 1 time.
The first time i get this error (at i=10):

[quote] *** Break *** segmentation violation
Using host libthread_db library “/lib/libthread_db.so.1”.
Attaching to program: /proc/17274/exe, process 17274
[Thread debugging using libthread_db enabled]
[New Thread -1225169200 (LWP 17274)]
Failed to read a valid object file image from memory.
0xb7f37410 in ?? ()
#1 0xbff91668 in ?? ()
#2 0x00000000 in ?? ()
Root > Function doit() busy flag cleared[/quote]

If i run the script for the second time I get the same error as before:

[quote]Error: illegal pointer to class object h[i] 0x0 986 histo.C:170:
*** Interpreter error recovered ***[/quote]

edit: the whole script

[code]doit(int file1, int file2, int detectornumber) {
TH1D *h[24]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Char_t filename[20],detectorname[20],outputfile[20];
TH2D *detectorhisto;

for(Int_t i=file1; i<(file2+1); ++i) {
Int_t createfilename = sprintf(filename,"%u.root",i); //Creating xxxxx.root string
if(FileExists(filename)!=0) { //Does the file exists ?
TFile f = new TFile(filename);
Int_t createdetname = sprintf(detectorname,“N_%02u”,detectornumber);
detectorhisto = (TH2D
)f->Get(detectorname);
Int_t r = gRandom->Uniform(24);
if(!h[r]) {
h[r] = detectorhisto->ProjectionX();
h[r]->SetDirectory(0);
}
h[r]->Add(detectorhisto->ProjectionX());
}
f->Close();
}

//Save all 24 histograms
for(Int_t i=0;i<24;++i) {
Int_t createoutputfile = sprintf(outputfile,“output_%02u_%s.root”,i,detectorname);
TFile savehistofile(outputfile,“recreate”);
h[i]->Write();
}

}[/code]

edit2:
Seems like the problem was that my (test)input was too small so not all h[i] were used/filled. By making the input larger so all h[i]'s were filled the whole program runs without errors.

It looks like instead of h[i]->Write(); you should use i f (h[i]) h[i]->Write();

Philippe

That would be indeed a good idea. Thank you.