J. *_*man 1 c struct variable-declaration type-declaration
假设我们有两个不同的struct主要是常见字段,但有一个或两个不同的字段或更少的字段.例如:
typedef struct HobbyNodetag {
char *name; // hobby name
struct HobbyNodetag* link; // link to next HobbyNode
int count; // number of times this hobby was mentioned by user
// more fields...
// but identical type/variable name with MyHobbyList
} HobbyNode; // database of entire hobby node; singly linked list
typedef struct MyHobbyTag{
char *name; // hobby name
struct MyHobbyTag* link; // linked to next MyHobbyNode
// more fields...
// but identical type/variable name with EntireHobbyList
} MyHobbyNode; // single person's hobby node; singly linked list
Run Code Online (Sandbox Code Playgroud)
我们是否有更高效/优雅的编码习惯才能使用以上两种struct?这不是浪费两个不同struct的,因为他们分享大部分领域?
UPDATE
我之前的问题是误导性的.上面的例子是节点并且单独链接(by link).
小智 6
您可以将所有额外字段(存在于第二个结构中但不存在于第一个结构中)移动到结构类型定义的末尾,然后使用较小的结构作为较大结构的"基础":
struct BaseFoo {
int count;
char name[128];
float value;
};
struct ExtendedFoo {
struct BaseFoo base;
struct ExtendedFoo *next;
};
Run Code Online (Sandbox Code Playgroud)
这个解决方案的优点是你可以拥有"多态":因为C标准保证在内存中第一个struct成员之前没有填充,这样就可以了:
void print_name(struct BaseFoo *foo)
{
printf("Count: %d\n", foo->count);
printf("Name: %s\n", foo->name);
}
struct ExtendedFoo foo = { /* initialize it */ };
print_name((BaseFoo *)&foo);
Run Code Online (Sandbox Code Playgroud)