struct accessing

David Olix dwho at nmtsun.nmt.edu
Tue Jun 27 06:39:39 AEST 1989


In article <1545 at stl.stc.co.uk> dsr at stl.stc.co.uk (David Riches) writes:
>I have a problem here which I'd like to get round if possible.
>Say I have a structure like :-
>
>struct fred
>  {
>   int tom;
>   int dick;
>   int harry;
>  }
>

OK, as long as all of the structure members are of the same type (in this
case int), there is a *slightly* sneaky way to handle it, although I admit,
it probably isn't the best thing for code readability.

Also I am assuming that the variable you have the name stored in is a
char * (or char[]).  In this case I have used 'name' as the variable.

Suppose you have the following:

struct fred {
  int tom;
  int dick;
  int harry;
   ...
};

char *people[] = {
  "tom", "dick", "harry", ...
};

char *name;
int i;
struct fred peoples;
int person;

...

for (i = 0; strcmp(people[i], name); ++i);
person = *((int *)&peoples + i);

Yeah, I know it's sleazy and nearly illegible, but it beats miles of case
statements.  Personally, though, if this is your problem, I would not define
fred as a structure, but rather as an array.

-- David Olix (dwho at nmtsun.nmt.edu)
"I take full responsibility for my own opinions,
   you take responsibility for yours!"



More information about the Comp.lang.c mailing list