Array of histograms

Hello All,

I would like to create a 3D array of TH1 histograms. I am fairly new to root and to C.

Array dimensions = 40 x 10 x 10;
I was able to successfully make a 2D array TH1 histograms but am confused about how I extend this to 3D.

This is what I have for 2D:

/* 
//2D histograms
TH1I   *RHist[10][10];
for (int a=0;a<10;a++) {
  for (int b=0;b<10;b++){
    RHist[a][b] = new TH1I ("a","a",10,1,10);
  }
}
*/

// Extending this to 3D
	TH1I   **RHist[5][10][10];
	for (int c=0;c<5;c++){
		(TH1I *)RHist[c][10][10] = new *TH1I[10][10];
		for (int a=0;a<10;a++) {
			for (int b=0;b<10;b++){
				RHist[c][a][b] = new TH1I ("a","a",10,1,10);
			}
		}
	}

Could you please help with extending this to 3D? Many thanks.

Victor.

1 Like

[quote] TH1I **RHist[5][10][10];
(TH1I *)RHist[c][10][10] = new *TH1I[10][10];
[/quote]Sounds like it would be a 5D array …
Isn’t:TH1I *RHist[5][10][10]; for (int a=0;a<5;a++) { for (int b=0;b<10;b++){ for (int c=0;c<10;c++) { RHist[a][b][c] = new TH1I ("a","a",10,1,10); } } }what you are looking for?

Philippe.

That is what I assumed. But when I compile my code I get a segmentation error.

The minimal code to reproduce this error is attached (and also pasted below):

int pmod1 = 16;
int pmod2 = 48;	
int Detector = 40;
int XtalIndex1, XtalIndex2,moduleindex;
int HistPerDetector=pmod2*pmod1;
int debugevents=0;

TH1I	*TimeHist[Detector][HistPerDetector][HistPerDetector];

int ***HistogramIndex;

// Allocate memory
HistogramIndex = new int**[HistPerDetector];
for (int i = 0; i < HistPerDetector; ++i) {
	HistogramIndex[i] = new int*[HistPerDetector];

	for (int j = 0; j < HistPerDetector; ++j)
		HistogramIndex[i][j] = new int[Detector];
}

// Assign values
HistogramIndex[0][0][0] = 3.6;
HistogramIndex[1][2][4] = 4.0;

// De-Allocate memory to prevent memory leak
for (int i = 0; i < HistPerDetector; ++i) {
	for (int j = 0; j < HistPerDetector; ++j)
		delete [] HistogramIndex[i][j];

	delete [] HistogramIndex[i];
}
delete [] HistogramIndex;

return EXIT_SUCCESS;
g++ -Wall `root-config --cflags --glibs` test.C -o test

[quote=“pcanal”][quote] TH1I **RHist[5][10][10];
(TH1I *)RHist[c][10][10] = new *TH1I[10][10];
[/quote]Sounds like it would be a 5D array …
Isn’t:TH1I *RHist[5][10][10]; for (int a=0;a<5;a++) { for (int b=0;b<10;b++){ for (int c=0;c<10;c++) { RHist[a][b][c] = new TH1I ("a","a",10,1,10); } } }what you are looking for?

Philippe.[/quote]
test.C (1.27 KB)

Hi,

The problem is that test.C allocates the stack:TH1I *TimeHist[40][768][768];which is requesting 180Mb … whereas a typically the default maximum stack size is around 10Mb. You can either increase this limit via (ulimit) if you admin allows it or you need to allocate this array of the help (via new). Probably the simplest solution is to migrate to using std::vector.

Cheers,
Philippe.