c - 从函数将值分配给全局结构

标签 c struct scope pass-by-reference function-definition

我正在从书本上学习 C,并且尝试了各种东西以便更好地理解这门语言。 我正在尝试将值从函数传递到全局结构。我遇到了麻烦,因为我执行 printf 来查看值是否确实已传递,但结果显示不同的值:

#include <stdio.h>

void receive_date(); //prototype of the function


struct date_example {
    int day;
    int month;
    int year;
};

int main()
{
    struct date_example d;
    receive_date();
    //this line below shows different values than those provided by the scanf inside the function
    printf("the day is %d and the month is %d and the year is %d",d.day,d.month,d.year); 
    return 0;
}



void receive_date(void)
{
    struct date_example d;
    printf("give day: \n");
    scanf("%d", &d.day);
    printf("give month: \n");
    scanf("%d", &d.month);
    printf("give year: \n");
    scanf("%d", &d.year);
    printf("the date is: %.1d %.1d %.1d \n", d.day, d.month, d.year );
}

结果如下:

give day:
2
give month:
3
give year:
2021
the date is: 2 3 2021
the day is 32758 and the month is 0 and the year is 0  // this is the part that gives different values
Process finished with exit code 0

最佳答案

您没有全局结构,即没有全局且结构类型的变量。只有类型声明是“全局”的。

更明确地说,这行代码有两次,每个函数一次。

struct date_example d;

main() 中的变量创建一个局部变量,只能从 main() 访问该变量。
receive_date 中的日期在那里创建一个本地日期,这是从该函数中提及它的所有行访问的日期。

因此,无论您在 receive_date 内执行的操作都会影响本地日期,但不会影响另一个本地日期,而另一个日期是 main() 的本地日期。

您在该函数内从该函数本地的 d 中 printf 的内容与 main() 中/从 main() 中不相关且不可见。

如果您确实希望在第二个函数中对 d 所做的任何操作都具有从 main() 中可见的效果,那么您需要删除这两行相同的行并在两个函数之外创建一个函数,即在 main() 之外和另一个函数之外。它将定义一个全局d,可以从两个函数访问它。

但是,“你需要”仅指你的学习实验。
实际上不推荐使用全局变量的设计。
您最好使用返回值或(可能比当前稍微高级一些)指向变量的指针参数来从函数内进行操作。

关于c - 从函数将值分配给全局结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71115342/

相关文章:

c - 基本指针用法

C 库与编译器一起分发还是直接由操作系统分发?

python - 如何遍历和搜索 python 字典?

c++ - 指向 POD 结构的 C/C++ 指针也指向第一个结构成员

javascript - 如果变量尚未传递给函数,则初始化该变量。这是正确的方法吗?

c - fread() 返回不正确的数据

c - 在 C 中分配矩阵

c - 如何通过指针将结构元素结构传递给函数

c++ - 引用文献 : am I going to go out of scope?

c++ - 在 C++ 中声明一个没有初始化的全局变量