arrays within structs

toughwimp11

Senior member
May 8, 2005
415
0
76
I'm working in C and basically, I would like to use arrays of a stuct in another struct. example:

struct dum {
int a;
};

typedef struct dum dum;

struct hor {
dum *hordum;
};

typedef struct hor hor;



int main() {
hor *hd;
hd= (hor *) malloc(sizeof(hor));
hd->hordum=calloc(5,sizeof(dum));
(hd->hordum[0])->a=5;
(hd->hordum[1])->a=8;
}

This of course doen't work but hopefully you can the see the gist of what I'm trying to do. Is there an easy way to do this?
 

Cogman

Lifer
Sep 19, 2000
10,286
147
106
:) your going to kick yourself when you see the solution.

(hd->hordum[0])->a=5;
(hd->hordum[1])->a=8;

should be

(hd->hordum[0]).a=5;
(hd->hordum[1]).a=8;

the [] operator dereferences the the dum pointer returning a dum struct, not a dum struct pointer. (also, you can take out the parenthesis if you like. Whichever is more readable for you)
 

toughwimp11

Senior member
May 8, 2005
415
0
76
thanks alot!!!
i have one more question. this is for a homework assignment and we're supposed to use dynamic storage allocation,
will i still be able to free all the dum structs once i'm done with them? and if so, how?
 

Cogman

Lifer
Sep 19, 2000
10,286
147
106
look up free. Basically, you just say free(hd->hordum) and then free(hd) to ensure there is no memory leaks.
 

toughwimp11

Senior member
May 8, 2005
415
0
76
hmm, doesn't seem to work.
in that case: is there a way to make it so that i can actually free the stucts.

lets say i have two dum structs that have already been allocated via malloc, is there a way to have those structs be in some sort of list in dumhor and a way so i can increment more dum structs to hordum?
 

Cogman

Lifer
Sep 19, 2000
10,286
147
106
So you want to increase the array size of hordum, correct?

If that's the case, then just call realloc, it will do the data copying for you.

but again, once you are done with the structs, you should always free them.
 

toughwimp11

Senior member
May 8, 2005
415
0
76
Could you give me an example?
Lets say I have:
hor *hd;
hd= (hor *) malloc(sizeof(hor));

now i want to add two dum to hordum, one with value 5 and one with value 6, how do i do this?

For example, if i have one dum called daaa (by the way, sorry for the crappy namings)
dum *daaa;
daaa= (dum *) malloc(sizeof(dum));
daaa.a=6;

and i want to append it do hordum, how would I do that?