mary
mary

Reputation: 355

C++ Allocation of array of struct

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?

Upvotes: 2

Views: 15263

Answers (4)

Sorin Adrian Carbunaru
Sorin Adrian Carbunaru

Reputation: 618

if you are programming in c++ you could use "new"...like: _Sample* data = new _Sample[size];

Upvotes: 0

Mesop
Mesop

Reputation: 5263

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
}

Upvotes: 6

Ed Heal
Ed Heal

Reputation: 59997

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

Upvotes: 3

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

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.

Upvotes: 5

Related Questions