views:

751

answers:

2
typedef struct {
        nat id;
        char *data;
        } element_struct;

typedef element_struct * element;

void push(element e, queue s) {
        nat lt = s->length;
        if (lt == max_length - 1) {
                printf("Error in push: Queue is full.\n");
                return;
        }
        else {
                s->contents[lt] = e;
                s->length = lt + 1;
        }
}
int main () {
         push(something_of_type_element, s);
}

How would i go about formatting "something_of_type_element"?

Thanks

Notes: nat is the same as int

+2  A: 

How about:

element elem = malloc(sizeof(element_struct));
if (elem == NULL) {
    /* Handle error. */
}

elem->id = something;
elem->data = something_else;

push(elem, s);

Note that there's lots of memory management missing here...

David Norman
+1  A: 

Like this:

element_struct foo = { 1, "bar" };
push(&foo, s);

If you have a C99 compiler you can do this:

element_struct foo = {
    .id = 1,
    .data = "bar"
};
push(&foo, s);

Note that the data in the structure must be copied if it needs to live longer than the scope in which it was defined. Otherwise, memory can be allocated on the heap with malloc (see below), or a global or static variable could be used.

element_struct foo = malloc(sizeof (element_struct));

foo.id = 1;
foo.data = "bar";
push(foo, s);
Judge Maygarden
That is going to behave very weird once you're going to use the queue contents outside of the function that calls push(), because structure defined like this is will live on its stack and get destroyed once the function exits.
che