这段代码是我试图为座位安排做不同的功能:
#include <stdio.h>
#include <stdlib.h>
#define NAME_LENGTH 200
#define NUMBER_OF_SEATS 12
有问题的结构:
//Create the struct (visible to all functions)
struct seat{
int id;
int marker; //0 for available, 1 for occupied
char customerName[NAME_LENGTH];
};
//Declare the array of struct (visible to all functions)
struct seat seats[NUMBER_OF_SEATS];
这是用于导航程序的菜单
void showNumberOfSeatsAvailable();
void assignASeat();
void deleteSeatAssignment();
void printSeats();
int main(void) {
setbuf(stdout, NULL);
int choice = 1;
int isQuit = 0;
//Initialize seats' ID
for(int i = 0; i < NUMBER_OF_SEATS; i ++){
seats[i].id = i + 1;
}
printSeats();
//User interaction
do{
//Step 1: Display the memu
puts("To choose a function, enter its number label:");
puts("1). Show number of seats available;");
puts("2). Assign a customer to a seat;");
puts("3). Delete a seat assignment;");
puts("4). Quit");
//Step 2: accept user input: the choice
scanf("%d", &choice);
//Step 3: Execute corresponding performance based on user choice
switch(choice){
case 1:
showNumberOfSeatsAvailable();
break;
case 2:
assignASeat();
break;
case 3:
deleteSeatAssignment();
break;
case 4:
isQuit = 1;
break;
default:
break;
}
if(isQuit == 1)
break;
}while(1 == 1);
return EXIT_SUCCESS;
}
void printSeats(){
}
我认为问题来自哪里
void assignASeat(){
char name[200];
puts("Implement the functionality of assigning a custumer to a seat");
//step 1: check if there is any seat available
int available;
for(int i = 0; i < NUMBER_OF_SEATS; i ++){
if(seats[i].marker ==0 ){
available++;
}
}
if (available >= 1){
printf("you're in luck! Theres Seats!n");
for(int i = 0; i < NUMBER_OF_SEATS; i ++){
if(seats[i].marker ==0){
seats[i].marker = 1;
printf("Enter Customer name: ");
scanf(" %c", seats[i].customerName[200]);
printf(" n");
seats[i].customerName[200] = name;
printf( " %c has been assigned a seatn",name);
break;
}
}
}
else {
printf("All seats are booked");
}
}
void showNumberOfSeatsAvailable(){
}
void deleteSeatAssignment(){
}
当我尝试设置客户名称的名称时,问题就来了。以下是我在浏览菜单并选择分配座位后的输出:
Implement the functionality of assigning a custumer to a seat
you're in luck! Theres Seats!
Enter Customer name: John doe
Segmentation fault
知道我为什么得到这个吗?我一直在环顾四周,但似乎可以找到解决方案。任何帮助都会很好。谢谢
不能在 C 中分配seats[i].customerName[200] = name
。要在 C 中复制字符串值strcpy()
应使用标准库函数。
char name[200];
printf("Enter the name:n");
scanf("%s",name);
strcpy(seats[i].customerName,name);
.
.