Passing a value using a struct to a function from C

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 do I go about formatting " something_of_type_element

"?

thank

Notes: nat is the same as int

+1


source to share


2 answers


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 is to live longer than the region in which it was defined. Otherwise, memory can be allocated on the heap using malloc (see below) or a global or static variable can be used.

element_struct foo = malloc(sizeof (element_struct));

foo.id = 1;
foo.data = "bar";
push(foo, s);

      

+1


source


What 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 is no memory management here ...

+3


source







All Articles