我的目标是在不使用实际成员的情况下调用结构的成员。听起来令人困惑,但这是我的示例代码以供进一步说明:
#include <stdio.h>
#include <conio.h>
#include <string.h>
typedef struct record
{
char name[50];
}REC;
int main()
{
REC r;
char input[50] = "name"; //goal is to access r.name
char test1[50] = "Successful!";
r.input = test1; //This returns an error obviously
}
我将char输入声明为“ name”作为REC结构成员之一。编译后,错误返回“ REC没有名为'input'的成员”。我如何使用“输入”来调用其中一个结构成员?预先谢谢你。
答案 0 :(得分:0)
基本上像这样:
if (!strcmp(input, "name"))
strcpy(r.name, test1);
else
printf("Invalid field!\n");
C不能提供根据其名称访问结构字段的方法。
也许您可以想到更聪明的方法来编写上述代码,但是无论采用哪种方法,都需要自己编写所有可能字段的列表。
答案 1 :(得分:0)
我没有弄清楚你的目标。似乎您想要struct变量的成员名称。但是成员名称(如果在定义结构时固定)是固定的。我只想像一下,也许您有几个不同的结构定义。在这种情况下,您可以按以下方式设置结构成员的值:
#include <stdio.h>
#define STR_SET(str,m,v) (str.m=(v))
#define MEM1 name
#define MEM2 age
typedef struct
{
char* name;
}REC_1;
typedef struct
{
char* age;
}REC_2;
int main(void)
{
REC_1 r1;
REC_2 r2;
char test1[50] = "Successful!";
STR_SET(r1, MEM1, test1);
STR_SET(r2, MEM2, test1);
}