C++ Allocation of array of struct

allocation, arrays, c++, struct

Solution

You are trying to create an array, for that, you should use `new[]` to allocate the memory (and `delete []` to deallocate it).

That way your code should be:

Sample* data = new Sample[nsamples];

Then you can iterate over each element of your array like any array:

for(int i = 0; i < nsamples; i++)
{
    data[i].contourY // do something
    data[i].contourX // do something
}

Problem

I have to allocate in C++ an array of struct, any struct contains two vector of int. This is my struct: ``` typedef struct _Sample{ vector<int> contourX; vector<int> contourY; }Sample; ``` To allocate this array I write the following code: ``` data = (struct _Sample*) malloc(sizeof(struct _Sample) * nsamples); ``` When I try to assign a Sample element to data[0] I have an error a runtime. Where is the problem?

Original source