I have quite a big structure which has inside of it other structures, then I want to pass this structure of structures as an argument of a function. Anyone knows how to do it or may give me an example please!
struct B {
//your struct..
};
struct A {
B b;
};
void foo(struct A a)
{
a.b + ???....
//you function
}
If your function doesn't need to modify any of the struct's contents, you can pass it like you would any other argument:
struct bigStruct {
struct aStruct a;
struct anotherStruct b;
struct someOtherStruct c;
...
};
void foo( struct bigStruct s )
{
do_something_with( s.a );
do_something_else_with( s.b );
...
}
If you need to write to any of the struct's members, you will need to pass a pointer to the struct, and use the ->
operator to access its members:
void bar( struct bigStruct *p )
{
do_something_with( p->a );
do_something_else_with( p->b );
....
}
Sometimes it's also desirable to use a pointer if the struct type is very large.
Note that you only need to use the ->
operator when dealing with a pointer to a struct. In our struct definition above, a
, b
, and c
are regular struct types, so we'd access their members with .
. For example, assuming the following definition for aStruct
:
struct aStruct {
int ival;
double dval;
char name[20];
};
we'd access those members through p
like so:
printf( "%d\n", p->a.ival );
printf( "%f\n", p->a.dval );
printf( "%s\n", p->a.name );
Now, if our bigStruct was defined like
struct bigStruct {
struct aStruct *a;
...
};
then we'd need to use the ->
operator for both the children of p
and the children of p->a
:
printf( "%d\n", p->a->ival );
printf( "%f\n", p->a->dval );
printf( "%s\n", p->a->name );
A structure may have both basic types and complex types as members. Passing a structure that has members that are in turn structures does not differ from passing a structure that only has basic type members.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.