Asperger Asperger - 24 days ago 5
C Question

passing specific struct field as function parameter

In javascript we can do the following:

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:

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?

Answer

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.

Comments