C:简单的程序编译正常但在某一点崩溃

标签 c arrays struct crash

当我使用或显示它们时,所有的值似乎都在它们应该在的位置,但出于某种原因,每次我到达某个点(在代码中标记)时,程序都会崩溃。

该程序应该向数组添加一个结构。此结构包含另一个 struct 以及一个表示数量的 int。这些也存储在数组中。

包括与崩溃相关的 main.c 和函数。

int main()
{
    int choice;
    int item_num;
    int item_amount;

    printf("*****MEAL PLANNER*****");

    while(choice != 0)
    {
        prepopulate();

        printf("\n\nTo view items, enter 1. \nTo view current menu, enter 2. \nTo add an item to the menu, enter 3. \nEnter 0 to exit.\n\n");
        scanf("%d", &choice);

        if(choice > 0 && choice < 5)
        {
            switch(choice)
            {
            case 1 : printf("\nView Items\n\n");

                displayAllFoodStuff();

                break;

            case 2 :printf("\nView Current Menu\n\n");
                display_meal();
                break;

            case 3 :printf("\nAdd Item to Menu\n\n");
                printf("Enter item number.\n");
                scanf("%d", &item_num);
                printf("Enter item amount.\n");
                scanf("%d", &item_amount);
                if(item_num <= fs_count)
                {
                    printf("Enter 1 to confirm.\n");
                    scanf("%d", choice);
                    fflush(stdin);
                    ////////CRASHING HERE!!!////////

                    if(choice == 1)
                    {
                        choose_food_item(food_list[item_num], item_amount);
                    }
                    break;

                }
                else
                {
                    printf("\nThat is not a valid entry.\n");
                }
                break;



            default: choice = 0;
                break;
            }
        }

    }

    return 0;
}

函数

//Define 'add_food_plan_item' function.
void add_food_plan_item(food_plan_item  fs)
{
    meal[item_count] = fs;
    item_count++;
}

//Define 'choose_food_item' function.
void choose_food_item(food_stuff fs, int qty)
{
    food_plan_item fpi;
    fpi.fs = fs;
    fpi.qty = qty;
    add_food_plan_item(fpi);
}

在此先感谢您提供的所有帮助。

最佳答案

您将 choice 传递给 scanf,但您打算传递 &choice。您的代码应为:

scanf("%d", &choice);

发生的事情是 scanf 需要一个地址来写入值。您传递的是值而不是值的地址,因此 scanf 将该值视为地址。因此,假设 choice 是一个值为 0 的变量。传递 choice 的值而不是其地址会导致 scanf 尝试写入地址 0。这通常会导致段错误。

关于C:简单的程序编译正常但在某一点崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20561045/

相关文章:

c - 在 C 中解码 Websocket 有效负载长度

c - ls命令如何找到硬链接(hard link)数?

python - main 中定义的 Numpy 数组在函数中无法识别

c - 已编辑 : incompatible types when assigning to type ‘struct Bar’ from type ‘struct Bar *’

sql - 在 BigQuery 中取消嵌套结构

c - 从双指针访问结构

c - 一次或逐行将内存分配给二维数组的区别

c 读取字符串导致崩溃

c++ - 在现代 C++ 中优雅地定义多维数组

javascript - document.write、Array.push 以及将字符串放在一起