Funny behaviour in loops

Dear root experts,
I experienced a funny behaviour with a for loops and std::vectors.

If I write in a macro the following lines:

files.push_back(new TFile(fileNames[0]));
cout << "files[0]->GetBestBuffer() " << files[0]->GetBestBuffer() << endl;
hTemp.push_back((TH1D*)files[0]->Get(“TurnOnMuon_1MuonIso_1Jet”));
(TH1D*)files[0]->Get(“TurnOnMuon_1MuonIso_1Jet”);
hTemp[0]->Draw();

It perfectly works. But if I put exactly the same lines in a for loop:

for(int i=0; i<fileNames.size(); i++) {
files.push_back(new TFile(fileNames[0]));
cout << "files[0]->GetBestBuffer() " << files[0]->GetBestBuffer() << endl;
hTemp.push_back((TH1D*)files[0]->Get(“TurnOnMuon_1MuonIso_1Jet”));
(TH1D*)files[0]->Get(“TurnOnMuon_1MuonIso_1Jet”);
hTemp[0]->Draw();
}

It crashes at the line hTemp.push_back((TH1D*)files[0]->Get(“TurnOnMuon_1MuonIso_1Jet”));

I noticed that, without the for loop, the line:
cout << "files[0]->GetBestBuffer() " << files[0]->GetBestBuffer() << endl;

gives as result 1024, in the for loop it gives 0. I really do not understand how the presence of the loop can change the file content. Any help will be apreciated.
Thanks,
Massimiliano

Do you really want to open file with name fileNames[0] fileName.size() times? Or it’s better use new TFile(fileNames[i]); ???

Do you really want files[0] or it should be files[i] ?