Thread: Basic Queue Question (or possibly typedef or struct question)

  1. #1
    Registered User
    Join Date
    Aug 2010
    Posts
    9

    Basic Queue Question (or possibly typedef or struct question)

    Hey everyone, I have a quick question about queues.

    So in a program I am making I need to make two queues, each of which will hold different typedef structs.

    For example, I have:
    1) typedef struct A
    2) typedef struct B

    In my program, I will have one queue of As and one queue of Bs.

    Now, in the node struct for my queue, I obviously need to determine the type of data that the node will hold (as do I need to use the type for the various functions for the queue). Is there a way to set the type of data in node to be some generic type that can be either A or B? If not, is there any other solution other than creating two "sets" of queue nodes, functions, struct, ect.?

    Any help is appreciated. If I'm not clear with my question, please tell me and I'll try to clarify.

    Cheers

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    The 'safe' way would be to have something like
    Code:
    struct node {
        struct node *next; // and prev if you want
        enum nodeType type;
        union {
            struct A a;
            struct B b;
        } data;
    };
    But
    - you don't have generic code without editing this struct.
    - it wastes memory if A and B have a large size difference.

    A 'generic' way is
    Code:
    struct node {
        struct node *next; // and prev if you want
        void *data;  // points at struct A or struct B or ...
    };
    But
    - you have to figure out separately what data is really pointing at.
    Which isn't too hard, if you have separate lists for separate types.
    - is two separate allocations (one for the node, one for the data)
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. help assignment due tomorrow
    By wildiv in forum C Programming
    Replies: 6
    Last Post: 01-27-2010, 08:38 PM
  2. Getting an error with OpenGL: collect2: ld returned 1 exit status
    By Lorgon Jortle in forum C++ Programming
    Replies: 6
    Last Post: 05-08-2009, 08:18 PM
  3. memory issue
    By t014y in forum C Programming
    Replies: 2
    Last Post: 02-21-2009, 12:37 AM
  4. Link List math
    By t014y in forum C Programming
    Replies: 17
    Last Post: 02-20-2009, 06:55 PM
  5. queue help
    By Unregistered in forum C Programming
    Replies: 2
    Last Post: 10-29-2001, 09:38 AM