Please consider the following code:
struct X
{
int x1;
int x2;
};
struct Y
{
int y1;
struct X *x;
};
Now I am allocating memory dynamically as follows:
struct Y *y = new Y[N];
And for each element of this structure array, I am also allocating memory for y[i].x as follows-
y[i].x = new X[M];
In such case, how does the system will allocate memory for y before knowing the actual memory size of y[i].x.
I am getting a segmentation fault in this case. Is there any good way to allocate memory dynamically? What if I need to reallocate memory (to grow the array size dynamically)?
xis always the same, it is a pointerstd::vector.std::vector.vectoris not just a fancy dynamic array. Note that yourstruct Yis broken in several ways. It can be copied, but bad things happen if you do. It can be used with automatic storage, but when it goes out of scope it leaks memory. It takes a lot more to get dynamic memory allocations right, something you dont want to rewrite each time, because someone else already did it for you:std::vector