TH1::SetTitle fails with a Form() input

I’m trying to generate a TH1 histogram title dynamically using Form(), but I get an unexpected error from the following MWE:

// run from command line as:
// $ root test_script.C
{
  Float_t x, y, z;
  TTree tree1("tree1", "new tree");
  tree1.Branch("x", &x, "x/F");
  tree1.Branch("y", &y, "y/F");
  tree1.Branch("z", &z, "z/F");
  for (int i = 0; i < 100; ++i) {
    x = 0;
    y = 1;
    z = 2;
    tree1.Fill();
  }

  TCanvas *c0 = new TCanvas("c0", "c0");
  c0->cd();
  tree1.Draw("z/sqrt(x*x+y*y+z*z)>>h0(100, -1, 1)", "", "e");

  h0->SetTitle(Form("hist title %d", 0));
}

Error message:

(myenv) jvavrek:~/project$ root test_script.C 
root [0] 
Processing test_script.C...
/Users/jvavrek/project/./test_script.C:19:16: error: cannot initialize an array element of type 'void *' with an rvalue of type 'char *(*)(const char *, ...)'
  h0->SetTitle(Form("hist title %d", 0));

If I remove the Form, the script runs fine:

tree1.Draw("z/sqrt(x*x+y*y+z*z)>>h0(100, -1, 1)", "", "e");
h0->SetTitle("hist title");

Alternatively, if I create the TString and assign it to a variable, the script runs fine:

tree1.Draw("z/sqrt(x*x+y*y+z*z)>>h0(100, -1, 1)", "", "e");
TString title = Form("hist title %d", 0);
h0->SetTitle(title);

Alternatively still, if I initialize the TH1D myself and then fill it, the script runs fine:

TH1D *h0 = new TH1D("h0", "h0", 100, -1, 1);
tree1.Draw("z/sqrt(x*x+y*y+z*z)>>h0", "", "e");

So somehow the title of a TH1 generated on-the-fly by TTree::Fill() interacts poorly with TString::Form().

ROOT Version: 6.24/06
Platform: Mac OSX 10.15.7
Compiler: Apple clang version 11.0.0 (clang-1100.0.33.17)


I don’t see that problem on Ubuntu 20.04, with ROOT 6.26/00. Instead, I get a different error (“use of undeclared identifier ‘h0’”), but I just create h0 before that, and Form works fine.

  TH1F *h0 = new TH1F("h0","h0", 100, -1, 1);

Creating h0 ahead of time is probably the “correct” way of doing it, but creating a histogram via the TTree::Draw() command was supported in the past.

See “Retrieving the result of Draw” and “Saving the result of Draw to a histogram” in the TTree::Draw method description.

1 Like

TH1D *h0 = (TH1D *)gDirectory->Get("h0"); works, thanks! I guess assuming h0 is accessible without that step works occasionally, but unreliably.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.