简体   繁体   English

在C语言中,如何在头文件中声明的main函数中使用结构?

[英]In C, how do you use a struct in the main function that was declared in a header file?

In C, I need to declare a struct linked list in a header file. 在C语言中,我需要在头文件中声明一个结构链接列表。 Within the main of my .c file, how do I declare a new instance of my struct? 在.c文件的主文件中,如何声明结构的新实例? Also should I use typedef for my struct? 我还应该对我的结构使用typedef吗?

In your header: 在标题中:

struct mystruct
{
int a;
int b;
};

in .c file include ( #include "header.h" ) the header, then use in main: 在.c文件中包含#include "header.h" )标头,然后在main中使用:

struct mystruct obj1;
obj1.a=0;
obj1.b=0;

In your header file add the definition and typedef 在头文件中添加定义和typedef

typedef struct linked_list_node_st {
    int val;
    struct linked_list_node_st *next;
} Linked_List_Node;

In main.c, call the struct using the typedef. 在main.c中,使用typedef调用结构。

#include <stdio.h>
#include <stdlib.h>
#include "structure.h"

int main(int argc, const char * argv[]) {
    Linked_List_Node *node;
    node = malloc(sizeof(Linked_List_Node));
    node->next = 0;
    node->val = 1;

    return 0;
}

U have struct in header, and want that struct in main.c? U在标头中具有struct,并在main.c中想要该struct吗? Just include it with #include "header.h" directive in your main.c, and start to use struct. 只需在main.c中使用#include“ header.h”指令将其包括在内,然后开始使用struct。

You use typedef when u want to make "your variable" in c , like: 当您想在c创建“您的变量”时,可以使用typedef,例如:

typedef int INTEGER;
INTEGER number;

So u use typedef for closer indentify your struct, for you or for readers. 因此,您可以使用typedef为您或您的读者更仔细地识别您的结构。

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

相关问题 如何在 header 文件中声明结构并在 .c 文件中定义它 - How do you declare a struct in a header file and define it in the .c file 如何为 C header 文件中声明的外部结构赋值或修改? - How do I assign values to or modify an extern struct declared in C header file? 当在另一个文件中声明struct时,如何使用struct作为函数的参数? - How to use struct as argument of a function when the struct is declared in another file? 在“ header.h”文件中声明一个自引用结构,并尝试在“ main.c”中定义它,这会导致错误 - Declared a self referential struct in 'header.h' file and trying to define it in 'main.c' and this causes error C:如何使用在 function A 中声明和定义的结构,在另一个 function B 中 - C : How to use a struct, declared and defined in function A, in another function B 在头文件中声明的函数在主文件中不可访问 - Function declared in header not accessible in main file 如何在另一个.c文件中使用前向声明的struct数据? - How to use forward declared struct data in another .c file? 从头文件调用Struct到主函数 - Calling Struct to main function from header file 在 C header 文件中声明的结构 - gcc Z224EDA3DC1D26B208EDCC3A08D317 错误 - Struct declared in C header file - gcc malloc error 函数在C头文件中声明两次 - Function declared twice in C header file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM