gpt4 book ai didi

C 编程 - "derived"类型的基本结构类型

转载 作者:行者123 更新时间:2023-11-30 14:57:14 25 4
gpt4 key购买 nike

这个想法是可以创建一个指向 Struct_A 实例的指针或
带有 BaseStruct 类型指针的 Struct_B 实例。

我可以使用任何编译器在 C 中创建“基本结构类型”吗?
我用 GCC 测试了它并且它有效,但我不确定它是否在任何地方都有效......

#include <stdio.h>

typedef enum {
StructType_A,
StructType_B
} StructType;

// >>> base type <<<
typedef struct {
StructType type;
} BaseStruct;

// >>> type A <<<
typedef struct {
StructType type;
int xyz;
char blabliblub;
} Struct_A;

// >>> type B <<<
typedef struct {
StructType type;
long int abc;
} Struct_B;

int main () {
Struct_A a;
BaseStruct* ptr;

a.type = StructType_A;
a.xyz = 7853;
a.blabliblub = 'z';

ptr = (BaseStruct*) &a;

if (ptr->type == StructType_A) printf ("YAY :3\n");
}

最佳答案

首先,回答你的问题,不允许用BaseStruct类型的指针指向Struct_B类型,如果这两种类型有不同的对齐要求(参见C standard):

6.3.2.3 Pointers

(7) A pointer to an object or incomplete type may be converted to a pointer to a different object or incomplete type. If the resulting pointer is not correctly aligned for the pointed-to type, the behavior is undefined.

但是,您可以通过建立适当的联盟轻松克服这种情况:

typedef enum {
StructType_A,
StructType_B
} StructType;

// >>> type A <<<
typedef struct {
int xyz;
char blabliblub;
} Struct_A;

// >>> type B <<<
typedef struct {
long int abc;
} Struct_B;

// >>> composite type <<<
typedef struct {
StructType type;
union {
Struct_A a;
Struct_B b;
} content;
} Union_AB;


int main () {
Struct_A a;
a.xyz = 7853;
a.blabliblub = 'z';

Union_AB anA;
anA.type = StructType_A;
anA.content.a.xyz = 7853;
anA.content.a.blabliblub = 'Z';

Union_AB someB;
someB.type = StructType_B;
someB.content.b.abc = 5653L;

Union_AB* ptr = (&anA);
if (ptr->type == StructType_A) printf ("YAY :3\n");

ptr = (&someB);
if (ptr->type == StructType_A) printf ("YAY :3\n");

return 0;
}

关于C 编程 - "derived"类型的基本结构类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44026427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com