Dynamically allocated array

Hello!

I am new to ROOT and OOP, in general.

I am trying to do a program that writes into a “.root” file a number of objects “Event” which containt a variable number of “Waveform” objects, “Waveform” having 1024 “x” coordinates and 1024 “y” coordinates.

When I use “task.C” program in which Waveform is statically allocated the program works well; when I open TBrowser and navigate to “output.root” -> waveform -> w[2] -> (let’s say) x, I see 4096 entries, but in the case of “task_dyn.C” I only see 2048 entries (nevent * 2).

My question is: am I doing right the dynamically allocation in the case of “task_dyn.c”? (because I think that’s the problem). I attached the two “.C” files I’m reffering.

Thanks in advance!


task_dyn.C (1.2 KB) task.C (1.1 KB)

Welcome to the ROOT forum!
You should use:

   w = new Waveform[noWaveforms];

instead of:

   w = (Waveform*) malloc(noWaveforms * sizeof(Waveform));
  • malloc allocates uninitialized memory.
  • new initializes the allocated memory by calling the constructor. It does not need you to manually specify the size you need and cast it to the appropriate type.
1 Like

Thank you @bellenot, but, unfortunately, this does not solves the problem.

I still have 2048 entries instead of 4096 (for nevent = 2 and noWaveforms = 2). This is how ROOT Object Browser looks like.

In the case of static allocation (Waveform w[2] instead of Waveform * w), ROOT Object Browser looks like this (this is how it should be).

I still can’t figure out what is the problem.

Thanks in advance!

I think there is something wrong in your code, since you only construct one Event class in both versions of your code… I’m trying to understand and I’ll let you know once I find what the issue is

Hello, @bellenot!

I solved the problem using “std::vector”. Here is the source code.

task_dyn.C (1.3 KB)

Thank you!

OK, good! And you’re welcome

1 Like