gpt4 book ai didi

在运行时在 c 中创建某个结构

转载 作者:行者123 更新时间:2023-12-05 03:14:49 24 4
gpt4 key购买 nike

我有一个任务,用户将在运行时为其指定他们想要创建的结构类型。

例如,假设用户输入:

姓名:char[50],地址:char[50],年龄:int

然后我的程序将必须创建一个包含这 3 种类型变量的结构。请注意,用户可以为结构指定任意数量的变量,但仅限于 char 和 int。

我的代码应该如何才能创建上面指定的结构?

这仅适用于 c 编程语言!

最佳答案

一个变量有3个字段:1) 类型,2) 姓名,3) 地址。你应该创建一个包含这 3 个结构的数组,这个结构的数组将是你想要的

您的结构可能如下所示:

typedef enum _Type{T_INT,T_STRING}Type;
typedef struct _var{
Type type;
char* name;
union {int n; char* str;} data;
}var;

typedef struct _Struct{
int count;
var* array;
} Struct;

当你得到输入后,你需要根据它构建Struct。姓名:char[50],地址:char[50],年龄:int

Struct *s = malloc(sizeof(Struct));
s->count = 3;//count of fields in the input
s->array = malloc(s->count*sizeof(var));
//you really should do it in a loop, after parsed the input...
for(i=0;i<s->count;i++){
s->array[i].name = strdup(parsedname);//"name", "address", "age"
s->array[i].type = strcmp(parsedtype,"int")?T_STRING: T_INT;
//for string you need to alloc memory for string...
if(s->array[i].type == T_STRING)
s->array[i].data.str=malloc(50 /*the size you've got*/);
//not need to alloc memory for the int
}

完成后不要忘记释放 mallocs:

for(i=0;i<s->count;i++){
free(s-array[i].name);
if(s->array[i].type == T_STRING)
free(s->array[1].data.str);
}
free(s->array);
free(s);

您还需要一个方法来填充结构并打印它,等等...

关于在运行时在 c 中创建某个结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22084223/

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