C++ Allocation of array of struct

12,234

Solution 1

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
}

Solution 2

Rule of thumb: Never use malloc in C++.1 It's a C function, and as such, doesn't do all the C++ stuff like calling constructors.

If you must dynamically allocate memory, use new instead.


1. This is a rule with a few exceptions, but for most cases is safe to treat as a blanket rule.

Solution 3

You need to use new - the constructors for your vectors need to be executed.

Share:
12,234
mary
Author by

mary

Updated on June 14, 2022

Comments

  • mary
    mary almost 2 years

    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?