[英]Segmentation Fault Error for a simple program in main() function
我剛開始自學 C,並想在 main() 中編寫一個基本程序,該程序將接受用戶輸入的密碼,使用正確的密碼進行檢查,並獲得適當的輸出。 然而,程序開始運行並讀取用戶輸入,但隨后突然在錯誤 Segmentation Fault (code dumped) 下終止。 導致錯誤的代碼有什么問題?
#include <stdio.h>
int main(void)
{
printf("Enter the password\n");
char guess;
scanf(" %c", &guess);
char password[] = "Hello123";
int correct = 0;
while (correct != 1){
if(strncmp(password,guess)==0){
printf("Success! You have logged in with your password
%c\n",guess);
correct +=1;
}
else
{
printf("Incorrect password. Try again\n");
}
}
}
嘿,我有幸重新編碼您的代碼
#include <stdio.h>
#include <string.h>
int main(void)
{
char *guess;
const char password[] = "Hello123";
int correct = 0;
while (correct != 1){
/*
* Include the input prompt inside while loop
*/
if (correct == 0){
printf("Enter the password\n");
scanf(" %s", guess);
}
if(strncmp(password,guess, 10)==0){ //strncmp accept 3 params, set length e.g 10
printf("Success! You have logged in with your password %s\n",guess);
correct = 1;
}
else
{
printf("Incorrect password. Try again\n");
correct = 0;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.