Initializing histograms in a subroutine

At most one year ago I used a subroutine to initialize histograms. This was very handy for making (multidimensional) arrays of histograms, passing in as arguments the array length, axis binnings and titles, naming scheme, etc.

Now with the same code, but a newer version of ROOT (5.34.05) (and probably different gcc version), I’m left with a null pointer. A very simplified example is below.

Any ideas on why this worked in the past but not now? Is this code even a “legal” thing to do?

void InitHist(TH1F* h,const char* name)
{
    h=new TH1F(name,"",10,0,10);
    cout<<"No Crash:    "<<  h->GetName()  <<endl;
}
void test()
{
    TH1F *h;
    InitHist(h,"h");
    cerr<<"Crash:   "<< h->GetName() <<endl;
}

[quote=“baltzell”]
Any ideas on why this worked in the past but not now? Is this code even a “legal” thing to do?

void InitHist(TH1F* h,const char* name) { h=new TH1F(name,"",10,0,10); cout<<"No Crash: "<< h->GetName() <<endl; } void test() { TH1F *h; InitHist(h,"h"); cerr<<"Crash: "<< h->GetName() <<endl; } [/quote]
What you do is “legal” but still doesn’t do what you think it does. In test()
you have a pointer h pointing to something. Then in InitHist you try to make
it point to a valid histogram, but you pass a copy to the pointer into the
function, so the assignment to h there is only seen in that function and not
outside of it. When you then call h->GetName() in test you still work with
whatever random memory h pointed to initally (try printing out the value of h
inside InitHist and in test before and after you call InitHist with cout << h << endl;).

To make InitHist work on the same h as the one in test you should pass a
reference instead, i.e. change the signature to

void InitHist(TH1F*& h,const char* name)

(read from right to left: “h is a reference to a pointer to a TH1F”).

Thank you very much, honk. My old code works again. I guess ROOT
used to silently correct for this mistake but no longer does.

I should mention that I realized I oversimplified my example. In order for
it to be what definitely used to work but now requires correct pointer/reference
usage, the example should have had the TH1, initialization subroutine, and the
code that calls it all as members of the same class.