使用scanf后Switch Case失效,输入操作值后程序直接终止
问题:输入action后程序立即终止,不执行switch分支
在为变量action输入值后,程序会立即终止,完全不执行switch语句中的任何分支。现附上驱动代码及运行输出,请问原因是什么?
驱动代码
int main() { // Creation of empty list struct Node* head = NULL; bool print = false; int action, placeNum, numIndex; while (print == false){ printf("LINKED LIST CREATOR \n"); printf("1. Insert node at the beginning\n"); printf("2. Insert node at the end\n"); printf("3. Insert node at specified position\n"); printf("4. Delete node at the beginning\n"); printf("5. Delete node at the end\n"); printf("6. Delete node at specified position\n"); printf("7. Display the linked list\n"); printf("Please enter the action you want to do: "); scanf("%d", action); switch (action) { case 1: printf("Enter the number to be placed at the beginning: "); scanf("%d", placeNum); insert_first(&head, placeNum); break; case 2: printf("Enter the number to be placed at the end: "); scanf("%d", placeNum); insert_last(&head, placeNum); break; case 3: printf("Enter the index for the number to be placed: "); scanf("%d", numIndex); printf("\nEnter the number to be placed at specified index: "); scanf("%d", placeNum); insert_middle(numIndex, placeNum, &head); break; case 4: delete_first(&head); break; case 5: delete_last(head); break; case 6: printf("Enter the index of the number to be deleted: "); scanf("%d", numIndex); delete_middle(&head, numIndex); break; case 7: printf("\nThe Created Linked List is: "); printList(head); print = true; break; } } return 0; }
运行输出
PS C:\Codes> cd "c:\Codes\C++\" ; if ($?) { g++ singlelist.cpp -o singlelist } ; if ($?) { .\singlelist } LINKED LIST CREATOR 1. Insert node at the beginning 2. Insert node at the end 3. Insert node at specified position 4. Delete node at the beginning 5. Delete node at the end 6. Delete node at specified position 7. Display the linked list Please enter the action you want to do: 1 PS C:\Codes\C++>
原因及修复方案
核心问题是**scanf的参数传递错误**:scanf要求传入变量的内存地址(指针),用于将输入值写入对应变量,但你直接传递了变量本身的值。
举个例子:
- 错误写法:
scanf("%d", action); - 正确写法:
scanf("%d", &action);
所有scanf调用都存在这个问题,比如:
scanf("%d", placeNum);→ 改为scanf("%d", &placeNum);scanf("%d", numIndex);→ 改为scanf("%d", &numIndex);
当错误传递变量值时,scanf会把该值当作内存地址去写入数据,这会触发非法内存访问,导致程序直接崩溃终止,根本无法进入switch分支执行。
修复所有scanf的参数,添加取地址符&后,程序即可正常执行switch逻辑。
内容的提问来源于stack exchange,提问作者Aldrin Lizardo
相关产品推荐
相关产品推荐

