简体   繁体   English

将具有struct类型的值传递给C中的函数

[英]Passing a value with struct type into a function in 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 would i go about formatting " something_of_type_element "? 我将如何格式化“ something_of_type_element ”?

Thanks 谢谢

Notes: nat is the same as int 注意:nat与int相同

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... 请注意,这里缺少大量的内存管理......

Like this: 像这样:

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

If you have a C99 compiler you can do this: 如果你有一个C99编译器,你可以这样做:

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. 否则,可以使用malloc在堆上分配内存(参见下文),或者可以使用全局或静态变量。

element_struct foo = malloc(sizeof (element_struct));

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM