c - 访问 C 中的全局结构数组
问题描述
简而言之问题
我在一个文件 ( ) 中更新了结构的全局数组add_product.c
,但无法在另一个文件 ( show_list.c
) 中打印这些更新。
细节
如果您需要完整图像,请查看github repo
这里是精髓。
我编写的程序让用户执行以下操作:
- 创建产品列表
- 在现有列表中添加产品
- 显示列表中的所有产品
...并由4个文件组成:
global-variables.h
main.c
show_list.c
add_product.c
global-variables.h
#define LIST_OF_PRODUCTS_INITIAL_LENGTH 50
struct Product {
char name[50];
float price;
unsigned int amount;
};
extern struct Product *list_of_products[LIST_OF_PRODUCTS_INITIAL_LENGTH];
extern unsigned int current_list_of_products_length;
main.c
struct Product *list_of_products[LIST_OF_PRODUCTS_INITIAL_LENGTH];
unsigned int current_list_of_products_length = 0;
add_product();
show_list();
add_product.c
int add_product() {
...
struct Product new_product;
list_of_products[current_list_of_products_length] = &new_product;
current_list_of_products_length++;
// For example, cheese
scanf("%s", &list_of_products[current_list_of_products_length]->name);
fflush(stdin);
scanf("%f", &list_of_products[current_list_of_products_length]->price);
fflush(stdin);
printf("Enter the amount of %s: ", list_of_products[current_list_of_products_length]->name);
scanf("%d", &list_of_products[current_list_of_products_length]->amount);
fflush(stdin);
list_of_products_exists = true;
// **NOTICE**! All the values here are printed correctly (cheese 15 150)
printf("Name: %s \n", list_of_products[current_list_of_products_length]->name);
printf("Price: %.2f\n", list_of_products[current_list_of_products_length]->price);
printf("Amount: %d\n", list_of_products[current_list_of_products_length]->amount);
...
};
show_list.c
问题就在这里!
int show_list() {
...
current_product = *list_of_products[0];
// EXPECTED cheese 15 150
// ACTUAL @6є 0 0.00
printf("%10s %10d %10.2f", current_product.name, current_product.amount, current_product.price);
...
}
解决方案
在函数中执行此操作:
struct Product new_product;
list_of_products[current_list_of_products_length] = &new_product;
...
一旦你在函数之外,就会产生未定义的行为。
这是因为此时局部变量new_product
不再可用,因此无法确定该地址&new_product
(在函数执行期间分配此变量的位置)处的内容。
推荐阅读
- python - Mac M1 中损坏的 Python
- android - Android 上的 Expo 图像压缩
- angular - 在页面上添加相同 Angular 元素的两个实例会中断路由
- c# - 有没有办法根据向导中的用户输入从 Visual Studio 项目模板中排除文件?
- javascript - 服务器集成测试
- c# - 如何解决 INSERT 语句与 FOREIGN KEY 约束“FK_Tickets_AspNetUsers_UserId”冲突
- dataframe - 加载多个 xls 文件、编辑和附加到一个数据帧中
- javascript - 如何在 Javascript 中组合函数
- apache-spark - Spark 到 JDBC:Py4JJavaError - 连接已启动,但没有一个提供者
- python - 如何从 PySpark 中的多个列创建字典列表,其中键是列名,值是该列的值?