Hi everyone,
my problem is related to how to set a large number of branches inside a TTree.
Writing a single line “tree->branch (…)” for every branch is a method that works, but it becomes heavy when the number of branches is increasing.
I tried this way:
for (i=0;i<numb_of_branches;i++) {
tree->branch(name[i], data+i, leaf_name[i]);
}
where data is the pointer to variables to be set for each branch.
This gives me an error called *** SEGMENTATION VIOLATION *** and I don’t know how to fix it.
Thank you,
Probably your bug is elsewhere (I assume yo are using tree->Branch with a capital B)
My best guess: your data variable (data + i) isn’t pointing to memory that is “yours”.
See this example (creates 2 trees with 5 Float_t and 42 Double_t branches)
// T can be std::array or std::vector of Float_t / Double_t / Long64_t / ...
template <typename T>
TTree *createTree(const char *name, T &data) {
auto tree = new TTree(name, name);
for (size_t i = 0; i < data.size(); ++i) {
tree->Branch(TString::Format("branch_%zd", i), &data[i]);
}
return tree;
}
void test() {
vector<Float_t> data1(5);
auto tree1 = createTree("tree1", data1); // creates Tree with 5 Float branches
// and fill 100 random event, set all values to 0..1
for (int i = 0; i < 100; ++i) {
for (auto &val : data1) val = gRandom->Uniform();
tree1->Fill();
}
tree1->Print();
vector<Double_t> data2(42);
auto tree2 = createTree("tree2", data2); // creates Tree with 42 Double_t branches
// and fill 42 random events, set all values to 23..42
for (int i = 0; i < 42; ++i) {
for (auto &val : data2) val = gRandom->Uniform(23, 42);
tree2->Fill();
}
tree2->Print();
// Note that data1 and data2 go out of scope here, so the branch addresses become invalid
// so you might want to reset the addresses
tree1->ResetBranchAddresses();
tree2->ResetBranchAddresses();
}