Creating histograms in separate functions

Hello.

I have a lot of similar histograms that I need to set up, so I would like to write a function that does the set up to reduce the amount of copy-paste and to make the code easier to maintain. However, I run into a problem. This peace of code for the array of histograms works fine:

1 void setHistos(TH1D* h[1]){
2 h[0] = new TH1D(“histo”,“result”,10,-4.5,4.5);
3 }
4
5 void arrayhisto(){
6 TH1D *his[1];
7 setHistos(his);
8 his[0]->SetBinContent(2,3);
9 his[0]->Draw();
10 }

but if I try similar definition with a single histogram:

1 void setHisto(TH1D *h){
2 h = new TH1D(“histo”,“result”,10,-4.5,4.5);
3 }
4
5 void singlehisto(){
6 TH1D *his;
7 setHisto(his);
8 his->SetBinContent(2,3);
9 his->Draw();
10 }

I get this error: Error: illegal pointer to class object his 0x0 601 singlehisto.C:8:

Could anybody tell me what I’m doing wrong and how would this work for a single histogram?

Cheers,
Jussi

Hi,

you need to pass a TH1*& or the function will operate on a copy of the parameter’s pointer.

Cheers, Axel.

Thanks, it works now. But why does the code for the array of histograms only work without &?

Cheers,
Jussi

Hi,

an array passes the address. Think of main(int, char** argv) being equivalent to main(int, char* argv[])

Cheers, Axel.