Correct way to initialize array of histograms?

Hi Rooters,

I was trying to send an array of histograms to a class and realized through the highlighting of my editor that I might be using a weird or unnecessary way of declaring my arrays of histograms. So far I used (because I found it somewhere on Google)

TH1F** h = new TH1F*[int];
...
delete[] h;

This worked so far but I never really understood the right syntax of delete for different scenarios, meaning when to use delete[] h or delete h or even something like delete() h. So it would be great if you could explain what the real difference is and when to use which method or send me a link to this topic. :slight_smile:

The other thing that bothers me: What is the difference to

TH1F* h[int];

? Is one better than the other or is there a deeper concept beneath that I simply didn"t grasp?

Your help is much appreciated! :slight_smile:

ROOT Version: 6.22/02
Platform: Centos7


Hi Martin,

For delete vs. delete[]: They need to match the new or new[] invocation. The version with brackets creates storage for arrays, the one without brackets creates a scalar object. The version with parentheses (delete()) I haven’t seen, I think.

The difference between the first approach with new[] and the second approach is mostly the lifetime of the array. The first approach is called “heap allocation”, and the created array stays alive until the delete[] call. In the second case (TH1F* h[int]), called “stack allocation”, the array will only live until the end of the current scope. At the end of the scope, it is automatically removed from the stack (no delete[] call). The histograms in the array, however, will in both cases stay alive until they are explicitly deleted.

I’d suggest to avoid dealing with raw arrays if possible. You can instead use an std::vector, e.g.

std::vector<TH1F *> histograms;
histograms.push_back(new THF1(...));
...

// You can access the std::vector like an array
histograms[0]->Fill(...);

// And you can pass it to a class that requires a pure array
FuncThatTakesHistArray(histograms.data());

Cheers,
Jakob

Thank you very much for this great explanation Jakob, I somehow never found this written down explicitly.
The approach with vectors didn’t really cross my mind but it does look intriguing. Thank you for that suggestion! :slight_smile: