简体   繁体   English

将特定的struct字段作为函数参数传递

[英]passing specific struct field as function parameter

In javascript we can do the following: 在javascript中,我们可以执行以下操作:

var obj = {alpha: [1, 2, 3], omega:[1, 2, 3]};

function test(field) {
   return obj[field];
}

test("alpha");

Now im trying to achieve the same in c using a typedef struct in c: 现在,我试图在c中使用typedef结构来实现相同的效果:

typedef struct FooBar{
   char alpha[50];
   char beta[50];
} FooBar;

FooBar fooBar;

int getTest(type field) {
    return sizeof(fooBar.field);
}

getTest(alpha);

Is it possible to somehow just pass in a field name like shown above? 是否可以通过某种方式像上面所示那样传递字段名称?

You could do it with a macro: 您可以使用宏来做到这一点:

#define getTest(t) sizeof(fooBar.t)

typedef struct FooBar {
  char alpha[50];
  char beta[50];
} FooBar;

FooBar fooBar;


int main()
{
  int alphasize = getTest(alpha);
}

But I'm not sure if this fulfills your requirement. 但是我不确定这是否满足您的要求。

No, you cannot achieve this straightaway. 不,您无法做到这一点。 When array names are passed to a function as argument, it decays to the pointer to the first element of the array, so from inside the called function, you cannot directly get the size of the original array, in general. 将数组名称作为参数传递给函数时,它会衰减到指向数组第一个元素的指针,因此通常,从被调用函数内部,您无法直接获取原始数组的大小。

However, if your array has a special sentinel value, then it can work, but that is a conditional scenario. 但是,如果您的数组具有特殊的哨兵值,则它可以工作,但这是有条件的情况。

No, the members of structs cannot be referenced as variables. 不可以,结构的成员不能作为变量引用。 Note that C is a compiled language. 请注意,C是一种编译语言。 At runtime, the information about the identifiers used for members is no longer present. 在运行时,有关用于成员的标识符的信息不再存在。

You would need to use separate functions for each member, such as 您需要为每个成员使用单独的函数,例如

size_t getAlphaSize(void) {
    return sizeof(fooBar.alpha);
}

Also note that sizeof returns an unsigned value of type size_t , not an int . 还要注意的是sizeof返回类型的无符号价值size_t ,而不是int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM