Asperger
Asperger

Reputation: 3222

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?

Upvotes: 1

Views: 62

Answers (3)

Jabberwocky
Jabberwocky

Reputation: 50774

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.

Upvotes: 4

Jens
Jens

Reputation: 72657

No, the members of structs cannot be referenced as variables. Note that C is a compiled language. 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.

Upvotes: 1

Sourav Ghosh
Sourav Ghosh

Reputation: 134336

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.

Upvotes: 1

Related Questions