is it possible to access members of struct in loop?

E

Erich Pul

hi!

is it possible to access the members of a struct (e.g. 10 members) in a
loop, comparable to an array?

tia,

E
 
G

Gordon Burditt

is it possible to access the members of a struct (e.g. 10 members) in a
loop, comparable to an array?

If you're expecting to iterate over the members of unknown name and
type, NO. You can make a table of the member names, types, and
offset (using offsetof()), and use that, but you have to keep it
up to date with the real struct, and it's messy.

If you need this, you probably want an array as a struct member.

Gordon L. Burditt
 
I

Ian Collins

Erich said:
hi!

is it possible to access the members of a struct (e.g. 10 members) in a
loop, comparable to an array?
No (unless those 10 members happen to be an array!), C has nothing like
the foraech construct found in some other languages.
 
E

Erich Pul

No (unless those 10 members happen to be an array!), C has nothing like
the foraech construct found in some other languages.

thank you - i will pack the values in an array and have my loop go
through it

E
 
D

Dave Thompson

hi!

is it possible to access the members of a struct (e.g. 10 members) in a
loop, comparable to an array?
As others have said, no. There are two things you can do that may, or
may not, approach this closely enough for your purpose:

enum { height /* = 0 */, width /* = 1 */, depth /* etc. */, NUMDIM };
struct dims { double dim [NUMDIM /* or 3 */]; } foo;

.... volume = foo.dim[height] * foo.dim[width] * foo.dim[depth]; ...

/* best not to use simple names like height because a macro
takes the identifier 'out of play' for ALL other use */
#define d_height dim[0]
#define d_width dim[1]
#define d_depth dim[2]
#define d_NUMDIM 3
struct dims { double dim [NUMDIM]; } foo;
.... volume = foo.d_height * foo.d_width * foo.d_depth; ...


- David.Thompson1 at worldnet.att.net
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top