1
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

1
  • 1
    This is just my opinion, but I think it's rather confusing to typedef a pointer type. For the sake of clarity, I would only typedef the struct. That way someone reading your code will know a pointer is being dealt with without having to already know the typedefs. Commented Mar 9, 2010 at 21:56

2 Answers 2

3

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...

Sign up to request clarification or add additional context in comments.

Comments

1

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);

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.