Thread: struct question

  1. #1
    Registered User
    Join Date
    Jul 2006
    Posts
    4

    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!

  2. #2
    Registered User Tonto's Avatar
    Join Date
    Jun 2005
    Location
    New York
    Posts
    1,465
    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++;
    	}
    }

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >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.
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help with linked list sorting function
    By Jaggid1x in forum C Programming
    Replies: 6
    Last Post: 06-02-2009, 02:14 AM
  2. Struct question... difference between passing to function...
    By Sparrowhawk in forum C++ Programming
    Replies: 6
    Last Post: 02-23-2009, 03:59 PM
  3. Looking for a way to store listbox data
    By Welder in forum C Programming
    Replies: 20
    Last Post: 11-01-2007, 11:48 PM
  4. struct question
    By caduardo21 in forum Windows Programming
    Replies: 5
    Last Post: 01-31-2005, 04:49 PM
  5. towers of hanoi problem
    By aik_21 in forum C Programming
    Replies: 1
    Last Post: 10-02-2004, 01:34 PM