Tag: global

将变量从全局变为本地 – C

我为一个项目编写了以下代码,但它没有通过单一测试,要求两个变量不是全局的,而是在main()本地。 修改structexample1.c ,使变量student和anotherStudent不是全局变量,而是main的本地变量。 我模糊地理解了本地和全球的概念,但我不确定如何在我编写的代码中实现问题。 #include #include struct student_s { char* name; int age; double height; struct student_s* next; } student; struct student_s anotherStudent; void printOneStudent(struct student_s student) { printf(“%s (%d) %s %s %.2lf %s\n”, student.name, student.age, “,”, “height”, student.height, ” m”); } void printStudents(const struct student_s* student) { while (student != NULL) { printOneStudent(*student); student […]

C90:如何在没有C99扩展的情况下在C中全局初始化此结构

我想知道用C90初始化这个结构的最好方法是什么,同时仍保持整洁。 在我的头文件中,将其命名为test.h,我定义了以下结构: struct s_test_cfg{ char *a[3]; char *b[3]; char *c[3]; } 然后我将它声明为extern结构,以便我可以在.c文件中全局初始化它: extern struct s_test_cfg test_cfg; 现在在我的.c文件中,我希望能够在全局范围内声明这样的东西(显然我要编写的内容在C90中不受支持): struct s_test_cfg test_cfg = { .a = {“a”, “b”, “c”},\ .b = {“d”, “e”, “f”},\ .c = {“g”, “h”, “i”} }; 这显然使你对你想要做的事情非常整洁和透明。 如何初始化我的C文件中的全局结构,该结构也像这种语法一样干净? 谢谢。

可以在.h文件中声明静态全局变量吗?

static关键字将全局变量的范围限制为该转换单元。 如果我在.h文件中使用static int x并且每隔一个文件包含该.h文件,它们是否都属于同一个翻译单元? 那么,到处都不会看到x吗? 那么静态的作用是什么? 另外,有没有使用static const int x ,其中x是一个全局变量? 默认情况下,并非所有const全局变量都是静态的 并且const变量的范围仅限于TU,即使它被限制在文件中的for循环中?

默认情况下全局变量是extern还是等于在全局中使用extern声明变量?

我经历了两个问题, C和C ++中的静态和外部全局变量 C中的全局变量是静态的还是不是? 这两个问题以不同的方式说明了这两件事。 问题1的答案: Global variables are not extern nor static by default on C and C++. 问题2的答案: If you do not specify a storage class (that is, the extern or static keywords), then by default global variables have external linkage 我需要知道以下内容。 默认情况下,全局变量是extern在链接(或)中它是否相当于通过指定extern存储类来声明变量? 2.默认情况下,全局变量在范围(或)中是静态的,它等同于通过指定静态存储类来声明变量? 3.如果有任何c或c ++差异请澄清?