Getting the mean value from TBranch variable

I have a root file with some TTree inside. I want to calculate the average of some variable for each TTree. Following this topic I tried:

TH1F *h = new TH1F();
Part1->Draw("x>>h", "", "goff");
TH1 *h = gDirectory->Get("h");

and I get the error ROOT_prompt_3:1:6: error: cannot initialize a variable of type 'TH1 *' with an rvalue of type 'TObject *'

I also tried the other case:

 Part1->Draw("x", "", "goff");
TH1 *h = (TH1*)gPad->GetPrimitive("htemp");

and I get *** Break *** segmentation violation

The thing is that if I type htemp->GetMean() I get the correct result. However, if after this I do for example Part1->Draw("y", "", "goff"); I get a segmentation error again.

This is a very basic thing to do, but I have no idea what I am doing wrong.

The first error you get is because the gDirectory->Get() returns a pointer of type TObject, and so if you want to re-interpret it as a TH1 pointer, you need to cast it to TH1*:

TH1 *h = (TH1 *)gDirectory->Get("h");

The second error is a little harder to check without having more of your code. It looks OK and you are correctly casting to TH1*. Did you check to make sure that gPad is not “null”? (I know it should not be, but that is the most likely issue causing the segmentation violation.)

TH1F *h = new TH1F("h", "my histogram;x title;y title", 100, 0., 0.); // automatic bins
Part1->Draw("x >> h", "", "goff");
h->Print();

This works! I also had to remove the first line TH1F *h = new TH1F(); to avoid redefinition of h.

About the second suggestion, I find unnecessary having to define the TH1F object with that much detail since I just want to calculate the mean of the TBranch variable. I don’t really care about the range or the nbins of the histogram.

Thank you both!