Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Hi,
This is a C programming problem.
I've a structure with 100 members.
How can i print out all 100 members of the structure, and the respective values they hold, without having to output each member 100 times thru' the printf statement?

You can do it if your struct is effectively an array. That is, all consecutive fields that have the same data size (type) can be treated as an array.
For example, if you have a struct (or part of a struct) with 10 consecutive ints, you could do something like this:
struct ofInts {
int field0;
int field1;
/* ... */
int field9;
};
int main() {struct ofInts MyStruct;
/* fill struct with data */
int *pStruct = (int*)&MyStruct;
/* or: (int)&MyStruct.field0; */for (int i=0; i<10; i++) {
printf("field %d = %d\n", i, pStruct[i]);
}
return 0;
}The compiler will lay down such a sequence of fields the same way it would an array: all sequentially in a single strip of mem. In the example above, the struct is really 10 contiguous ints, just like "int array[10];". By taking the address of the first field that begins a series of same-type values, you can iterate up to the last one, as shown. Casting can be very useful.
If the fields are a mix of sizes or types, you probably won't be able to do the same thing. You could, however, keep a table of offsets into the fields, then add them to the base address of the struct to get to each field in a for loop, but that would be nearly as much work as your original problem.
Cheers

![]() |
Doubt in VB
|
Easy SQL question
|

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |