C程序为什么输入

时间:2017-04-18 22:09:07

标签: c

我有一些问题让我的输入进入,它在我输入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;
}

2 个答案:

答案 0 :(得分:0)

由于未初始化的变量&#34; count&#34;你得到一个段错误用于访问数组,导致您超出数组的范围。

您假设count具有一定值(0?)但实际上它具有创建变量时遇到的任何垃圾。你需要明确地说count = 0;

答案 1 :(得分:0)

  

功能中, 计数 已声明但尚未初始化,因此 count < / em> 具有无意义的值,您必须将 count 变量初始化为0

int main (void)
{ // OPENS MAIN


//  Declarations

int choice;
int count;        // --->>>> int count = 0;
struct item inven[MAX];
//...
}