struct within a struct question.

Started by
2 comments, last by red-dragonX 18 years, 6 months ago
hello, i have a question here and as retarded as it may be, i've tried but couldn't come up with the solution to this. I have a struct within a struct: typedef struct whatever blah; typedef struct whatever{ int x; } wht; typedef struct node { blah *something; //struct within a struct struct node* next; } node_w; I want to store/scanf data into field x of struct whatever using the 'struct within a struct'. i have to do this in C. would it be something like: scanf("%d", &head->something->x); it seems confusing the way i've explained this but i don't know how else to ask. oh and while that compiles, it'll ask me for data, then I get a segmentation fault. thanks in advance.
Advertisement
You probably get a segfault because you haven't actually allocated anything. Either change blah *something to blah something (and scanf("%d", &head->something->x); to scanf("%d", &head->something.x);) or allocate the data with new/malloc depending on whether you are using C or C++ (I suppose you are using straight C?).


jfl.
your syntax for accessing the struct-in-a-struct is correct. However, when using at runtime, ensure that the struct-in-a-struct is allocated. You're using a pointer, so an allocation is required before u can use that second level of indirection.
- To learn, we share... Give some to take some -
thanks to both of you, resolved the issue.


This topic is closed to new replies.

Advertisement