Computing.Net > Forums > Programming > C structures

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Click here to start participating now! Also, check out the New User Guide.

C structures

Reply to Message Icon

Name: Jim
Date: November 18, 2002 at 05:24:23 Pacific
OS: windows
CPU/Ram: 128
Comment:

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?



Sponsored Link
Ads by Google

Response Number 1
Name: Jeff J
Date: November 18, 2002 at 07:03:39 Pacific
Reply:

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


0
Reply to Message Icon

Related Posts

See More


Doubt in VB Easy SQL question



Post Locked

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


Go to Programming Forum Home


Sponsored links

Ads by Google


Results for: C structures

C Structure www.computing.net/answers/programming/c-structure/16957.html

Need help from C www.computing.net/answers/programming/need-help-from-c/5737.html

Learning to program with C: A viable opt www.computing.net/answers/programming/learning-to-program-with-c-a-viable-opt/391.html