gpt4 book ai didi

C程序为什么输入后就崩溃了

转载 作者:行者123 更新时间:2023-11-30 19:34:44 25 4
gpt4 key购买 nike

我在输入内容时遇到了一些问题,输入 itemID 后它就崩溃了,我完全迷失了方向,我正在使用数组,如果有人可以帮助我,那就太棒了。另外谢谢,我知道我的编码很糟糕。

#include <stdio.h>
#include <stdlib.h>
#define MAX 3

//Structed Items

struct item{

char itemname[20];
char itemdes[30];
int itemID;
int itemOH;
double itemUP;
};


// Function Declarations

int getMenu_Choice ();
int process (int choice, int count, struct item inven[]);
int add (int count, struct item inven[]);
int showall(int count, struct item inven[]);


int main (void)
{ // OPENS MAIN


// Declarations

int choice;
int count;
struct item inven[MAX];


// Statements

do//
{
choice = getMenu_Choice ();
process (choice, count, inven);
}
while (choice != 0);


return 0;


} // CLOSE MAIN

/*============================getChoice=*/

int getMenu_Choice (void)
{ //OPEN GETCHOICE


// Declarations
int choice;

// Statements

printf("\n\n**********************************");
printf("\n MENU ");
printf("\n\t1.Create A File ");
printf("\n\t2.Read A File ");
printf("\n\t0.Exit ");
printf("\n**********************************");
printf("\nPlease Type Your Choice Using 0-2");
printf("\nThen Hit Enter: ");
scanf("%d", &choice);

return choice;

} //CLOSES GET CHOICE




/*============================process=*/

int process (int choice, int count, struct item inven[])
{// OPEN PROCESS


// Declarations


// Statements
switch(choice)
{
case 1: count = add(count, inven);
break;
case 2: showall(count, inven);
break;
case 0: exit;
break;
deafult: printf("Sorry Option Not Offered");
break;

} // switch

return count;

} // CLOSE PROCESS


/*============================add one=*/
int add(int count, struct item inven[])

{//OPENS CREATE

// Declarations

int i;


i = count;

if (count != MAX)
{
printf("Enter the Item ID:\n");
scanf("%d", &inven[i].itemID);

printf("Enter the Item Name:\n");
scanf("%s", &inven[i].itemname);
i++;

}

else {
printf("sorry there is no more room for you to add");

};

return i;


}; // CLOSE CREATE



/*============================showall=*/

int showall(int count, struct item inven[])
{
//Declarations
int i;

// Statements




for(i = 0; i < MAX; i++)
{
printf("\nItem ID : %d", inven[i].itemID);
printf("\nItem Name : %s", inven[i].itemname);
};

return 0;
}

最佳答案

由于使用未初始化的变量“count”来访问数组,您遇到了段错误,导致超出了数组的范围。

您假设 count 具有特定值(0?),但事实上,当您创建变量时,它具有恰好属于它们的垃圾。您需要明确地说 count = 0;

关于C程序为什么输入后就崩溃了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43483020/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com