首页 > 解决方案 > 访问 C 中的全局结构数组

问题描述

简而言之问题

我在一个文件 ( ) 中更新了结构的全局数组add_product.c,但无法在另一个文件 ( show_list.c) 中打印这些更新。

细节

如果您需要完整图像,请查看github repo

这里是精髓。

我编写的程序让用户执行以下操作:

  1. 创建产品列表
  2. 在现有列表中添加产品
  3. 显示列表中的所有产品

...并由4个文件组成:

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);

    ...
}

标签: c

解决方案


在函数中执行此操作:

struct Product new_product;
list_of_products[current_list_of_products_length] = &new_product;
...

一旦你在函数之外,就会产生未定义的行为。

这是因为此时局部变量new_product不再可用,因此无法确定该地址&new_product(在函数执行期间分配此变量的位置)处的内容。


推荐阅读