从用户定义的函数返回使我的程序崩溃

Returning From User Defined Function is Crashing My Program

所以我的目标是在函数内部将菜单选项作为输入 getMenuInput(); (1-4) 和 return 它到 main() 与开关盒一起使用。此代码已简化,但我打算轮询两个向量并对它们执行操作。我 life 无法弄清楚为什么它在 return 从函数中退出时停止,而没有到达开关盒。我什至尝试在 return 之后立即在行中打印文本,但没有输出。

作为旁注,您只有 3 次机会输入正确的菜单选项,否则程序将退出并打印错误。这(或者更确切地说,我实现这个的方法)会是这里的问题吗?

这是我的代码:

#include <stdio.h>

/* This is a structure to hold the two parts
of the vector in a single variable        */
typedef struct
{
    float x;
    float y;
} vect;

char getMenuInput(void);

int main(void)
{
    /* declaration of variables */
    vect vector1, vector2;
    char menuInput = 0;
    int counter = 0;

    while ((counter < 3) && (menuInput == 0))
    {
        printf("--- Menu ---\n"
           "1 Add two vectors\n"
           "2 Subtract two vectors\n"
           "3 Calculate Euclidian Distance\n"
           "4 Exit the program\n"
           "  Please select an option (1, 2, 3, or 4): ");

        menuInput = getMenuInput();  /* 3 chances */

        switch (menuInput)
        {
            case 1:
            {
                printf("You selected 'Add'\n");
                break;
            }/* Add vectors */

            case 2: 
            {
                printf("You selected 'Subtract'\n");
                break;
            }/* Subtract vectors */

            case 3: 
            {
                printf("You selected 'Euclidian Distance'\n"); 
                break;
            }/* Euc Distance */

            case 4: 
            {
                printf("You selected 'Exit'\n"); 
                break;
            }/* exit */

            default: 
            {
                printf("  >Invalid option!\n");
                menuInput = 0;
                ++counter;
            }
        }
    }
    if (counter == 3)
        printf("Program error - Too many invalid inputs");
    else
        return (0);

        /* Receive the two vectors (float or int, +ve or -ve */
        /* This repeats until they're entered correctly */


        /* Find the solution, operation found in the menu */
        /* Float, 2dp precision */
}

char getMenuInput(void)
{
    char temp;
    scanf("%d", &temp);
    return (temp);
}

我得到的输出是这样的:

--- Menu ---
1 Add two vectors
2 Subtract two vectors
3 Calculate Euclidian Distance
4 Exit the program
  Please select an option (1, 2, 3, or 4): 1

RUN SUCCESSFUL (total time: 870ms)

请帮忙。我正在扯头发。

char temp;
scanf("%d", &temp);

temp 是一个字符(1 个字节),但您正试图将一个整数(可能是 4 或 8 个字节)读入其中?这是很可能导致崩溃的未定义行为。

变量声明可能有误。 在创建结构时必须使用 vector 1,vector 2 而不是 Vect。而且您还没有在此代码中使用它。那你为什么要创造它?