Hello everyone,

I find C not very flexible this time because I know there is an easy way to assign field values to a struct like this :

Struct mine = { field1, field2, ... };

but in my case "mine" is contained in a bigger struct. So I have to assign let's say a field named data but it seems I cannot do :

parent->data = { field1, field2, ... };

Moreover data in my case is an array to full with these Struct. I wish I could simply do :

unsigned int i = 0;
parent->data[i++] = { field1, field2, ... };
parent->data[i++] = { field1, field2, ... };
// etc...

Is there any nice way to do it in C ? I can't understand why there is this kind of limitation ! The type are specified, there isn't any pointer but only memory assignment to do. Note that these fieldN are hard coded. Thank you.

Edited 6 Years Ago by Jamesbch: n/a

I don't believe there is a problem doing this, you're not bringing your pointers or member operator on down to the right level.

Using the dot operator, I would say:

parent.nameOfField.nameOfChildStruct.fieldIwant

You can do the same idea with pointers, of course.

Using the dot operator force me to copy and paste many times the same things. It's redundant, heavy, unreadable and not easily maintained. I prefer something as ugly as this :

unsigned int i = 0;
Struct A = { field1, field2, ... };
parent->data[i++] = A;
Struct B = {field1, field2, ... };
parent->data[i++] = B;
// And so on ...

But I would prefer something better. Has anyone an ingenious idea ?

When you declare nested structs, you can expect some redundancy in your code.

I'm thinking use something like:
#define PARENT and then put in all the outer structs and fields you need, so only
PARENT->YourSubStuctureFieldName would be all you need to access that nested field or struct.

How does that sound?

This article has been dead for over six months. Start a new discussion instead.