如果我有这样的结构:
/* Defined structure with 3 integer as members */
typedef struct MyStruct MyStruct;
struct Myscruct{
int x;
int y;
int z;
};
int main()
{
Mystruct example; // declared "example" with type "Mystuct"
example.x=1; // member 1 have value 1
example.y=2; // member 2 have value 2
example.z=3; // member 3 have value 3
char c;
printf("\nchoose witch member you want to print [ x, y or z]");
scanf("%c", &c);
while(getchar() != '\n');
printf("%d", example.c); // this is the part i don't know is possible.
return 0;
}
可以将不同的成员传递给最后一个printf而不是使用if的组合吗? 如果是这样,它的语法是什么?
答案 0 :(得分:0)
不,您不能使用运行时数据来引用源代码中的符号。但是,您可以通过更多的努力来完成特定代码的明显目标:
typedef struct MyStruct MyStruct;
struct Myscruct{
int x;
int y;
int z;
};
int main()
{
Mystruct example; // declared "example" with type "Mystuct"
example.x=1; // member 1 have value 1
example.y=2; // member 2 have value 2
example.z=3; // member 3 have value 3
char c;
int xyz;
printf("\nchoose witch membeer you want to print [ x, y or z]");
scanf("%c", &c);
switch (c) {
case 'x':
xyz = example.x;
break;
case 'y':
xyz = example.y;
break;
case 'z':
xyz = example.z;
break;
default:
puts("Oops\n");
return 1;
}
printf("%d", xyz);
return 0;
}
还有其他选择,但没有一个像你尝试的那样直接。
答案 1 :(得分:0)
你想要的是反射,而C却没有。
一种解决方案是让Mystruct
包含数组:
struct Mystruct {
int coordinates[3];
};
...
Mystruct example;
example.coordinates[0]=1;
example.coordinates[1]=2;
example.coordinates[2]=3;
int i;
然后询问用户一个数字,将其存储在i
中并将其用作数组的索引:
printf("%d", example.coordinates[i]);
答案 2 :(得分:0)
您可以使用offsetof
:
#include <stdio.h>
#include <stddef.h>
typedef struct MyStruct MyStruct;
struct MyStruct{
int x;
int y;
int z;
};
int main()
{
size_t addr[] = {
offsetof(MyStruct, x),
offsetof(MyStruct, y),
offsetof(MyStruct, z),
};
MyStruct example; // declared "example" with type "Mystuct"
example.x=1; // member 1 have value 1
example.y=2; // member 2 have value 2
example.z=3; // member 3 have value 3
char c;
printf("\nchoose witch membeer you want to print [ x, y or z]");
scanf("%c", &c);
printf("%d\n", *(int *)((char *)(&example) + addr[c - 'x']));
return 0;
}
输出:
choose witch membeer you want to print [ x, y or z]y
2