-
struct question
I'm writing this program that has a struct that contains a close to a dozen variables. I know that these variables can be accessed with the "." notation, however I was wondering if there is a way to access them with like a counter or a pointer.
What I need to do is to flush out the values using a for loop, so it increments through the variables within the struct. I tried googling and did a search on this forum and I could not get my question answered. Thanks in advance!
-
I don't know how legal and ethical and moral this is, I don't think it is legal at all but would like to be corrected if it is, but I think this is what you are asking. I don't know any other way to 'enumerate' structure members. This assumes that they are all the same type, and that the byte alignment isn't screwing anything up. I don't think I'm allowed to assume this however.
Code:
struct type
{
int a;
int b;
int c;
int d;
int e;
}
t = { 1, 2, 3, 4, 5 };
int main()
{
int * p = (int *) &t;
while((char *) p < (char *) &t + sizeof type)
{
(*p)++;
printf("%d\n", *p);
p++;
}
}
-
>I tried googling and did a search on this forum and I could not get my question answered.
Probably because your question doesn't have a good answer. The only relatively portable method I can think of would be to build a list of offsets from the offsetof macro and iterate through it. It's kind of messy though, and if the members have different types (they would have to, or you'd be using an array, right?) then it gets interesting. You might want to consider your design and try something different.
>I don't think I'm allowed to assume this however.
You aren't. Internal padding would break your method.