jankos
jankos

Reputation: 916

Dynamically Allocating a mulitple Struct within a Struct

I am new to C++ and need some help. I have the following code:

struct Force {
    float X[10];
    float Y[10];
    float Z[10];
};

struct Measurement{
    char serial_number[30];
    struct Force F1;
    struct Force F2;
 };

How should I properly allocate the following?

struct Measurement meas

The problem is that struct Force force works fine; however, when I try to define struct Measurement meas then I get "Unhandled exception" error!

Upvotes: 0

Views: 163

Answers (3)

dr4cul4
dr4cul4

Reputation: 268

Technically it works like you wrote it, but struct word is unnecessary on members (actually generates warning but works.)

struct Force {
    float X[10];
    float Y[10];
    float Z[10];
};

struct Measurement {
    char serial_number[30];
    Force F1;
    Force F2;
};

Then in function use like this:

Measurement somevar;
somevar.F1.Y = 999;

Now the proper way to do this (and save stack) is to use pointers.

struct Measurement {
    char serial_number[30];
    Force* F1;
    Force* F2;
};

And then:

Measurement* m = new Measurement;
if (m) {
    m->F1 = new Force;
    m->F2 = new Force;
}

After using you have to delete all pointers to avoid memory leaks:

delete m->F1;
delete m->F2;
delete m;

There is another approach. Using:

struct Force {
    float X[10];
    float Y[10];
    float Z[10];
};

struct Measurement {
    char serial_number[30];
    Force F1;
    Force F2;
};

You can allocate with malloc some amount of memory and treat it as struct (did not have time to test it, but I use that approach many times).

Measurement* m = (Measurement*)malloc(sizeof( size in bytes of both structs ));
// zero memory on m pointer

// after use
free(m);

That's all.

Upvotes: 1

huseyin tugrul buyukisik
huseyin tugrul buyukisik

Reputation: 11920

C:

struct Measurement *meas;
meas=(struct Measurement *) malloc(sizeof(Measurement));
              ^                             ^                         
              |                             |                 
              |                             |                
          this is shape                  this is the space allocated

C++:

Measurement *meas;
meas=new Measurement;

Upvotes: 0

jsist
jsist

Reputation: 5253

As I saw in your question, you are using C, so here is solution for C.

Wherever you want to have instance of structure Measurement, simply type:

struct Measurement meas;

and you will be able to access your structure elements as:

meas.F1.X and so on...

And if you wish to have dynamic allocation(i.e. at run time) then simply use malloc/calloc as follows

struct Measurement *meas = (struct Measurement *)malloc(sizeof(struct Measurement));

Doing so, you will have to access your structure elements as:

meas->F1.X and so on...

Upvotes: 2

Related Questions