Reputation: 355
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
Reputation: 618
if you are programming in c++ you could use "new"...like: _Sample* data = new _Sample[size];
Upvotes: 0
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
Reputation: 59997
You need to use new
- the constructors for your vectors need to be executed.
Upvotes: 3
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.
Upvotes: 5