下面是完整的代码
我的问题简要总结如下:我在 file1.c 中有一个全局结构,如下文所述,它通过函数"assign_value()"在 file1.c 中使用某个值进行初始化,现在我通过函数"print_value()"从 file2.c 打印此值。
问题是:另一方面,如果我在函数"assign_value()"中从 file1.c 调用"print_value()",它没有从 file2.c 打印正确的值,如下所述,那么它会显示正确的值。
请建议我缺少什么,为什么我无法通过在 file2.c 中调用 print_value() 函数来打印正确的值
file1.c
My_struct_one 是嵌套结构,包含另一个结构My_struct_two my_struct_obj_global是 file1.c 中的全局变量
//file1.c
#include <stdio.h>
#include "file1.h"
typedef unsigned long int List;
typedef struct
{
List* my_list;
}My_struct_two;
typedef struct
{
My_struct_two struct_two;
}My_struct_one;
My_struct_one struct_global;
void assign_value()
{
List value=9;
struct_global.struct_two.my_list = &value;
print_value();
}
void print_value()
{
printf("inside print");
printf("value=%un",*(struct_global.struct_two.my_list));
}
文件1.h 文件.h
#ifndef _file1_c
#define _file1_c
void print_value();
void assign_value();
#endif
文件2.c #include
#include "file1.h"
int main()
{
assign_value();
print_value();
return 0;
}
输出:内部打印值=9内部打印值=4195506
我的疑问是为什么我无法从 file2.c 访问值,
-
value
是函数assign_value()
中的局部变量。它在进入函数时创建,在函数返回时销毁。 -
在函数
print_value()
中,struct_global.struct_two.my_list
的值是一个悬空的指针:它的值是一个不再存在的变量的地址。 -
取消引用悬空指针的值是未定义的行为。