有人知道如何发送结构参数的名称作为自变量吗?我有这样的代码:
typedef struct {
double x;
double y;
double dis;
} Point;
void bucketSort (Point * points, name /*name of parameter*/)
{
printf("%lf",points.name);
}
例如,我看到的函数调用:
bucketSort(point1,"dis");
答案 0 :(得分:1)
我认为您不能将变量名作为参数发送。您可以按如下所示进行检查
typedef struct {
double x;
double y;
double dis;
} Point;
void bucketSort (Point * points,char *name /*name of parameter*/)
{
if(name[0] == 'd' ) printf("%lf",points.dis);
else if(name[0] == 'x') printf("%lf",points.x);
else if(name[0] == 'y') printf("%lf",points.y);
}
答案 1 :(得分:1)
您可以定义enum
并存储所有可能的名称。然后,您可以将此enum
用作函数的参数。
typedef enum {
ENUM_X = 0,
ENUM_Y = 1,
ENUM_DIS = 2
} STRCT_PARAM_NAME;
typedef struct {
double x;
double y;
double dis;
} Point;
void bucketSort (Point * points, STRCT_PARAM_NAME name) {
switch (name) {
case ENUM_X: printf("%lf\n", points->x); break;
case ENUM_Y: printf("%lf\n", points->y); break;
case ENUM_DIS: printf("%lf\n", points->dis); break;
default: printf("Invalid\n"); break;
}
}
现在,您可以像这样呼叫bucketSort
:
bucketSort(points_obj, ENUM_X);