[英]C segmentation fault on linux with strncmp
這有效(“ Y”必須為單引號):
if (toupper(user_input(2)) == 'Y') printf("you said y");
這會產生細分錯誤:
if (!strncmp((char *)toupper(user_input(2)), "Y", 1)) printf("you said y");
strncmp必須走的很深,但不確定為什么,因為我將強制轉換的toupper()傳遞為(char *)。 沒有強制轉換,同樣的錯誤。
僅供參考user_input()是(NB變量是全局的):
char* user_input(int size) { //size is the number of characters to capture. Remember to account for \n or \0
if (fgets(buf, size, stdin) != NULL) { //buf is char buf[1000];
if ((p = strchr(buf, '\n')) != NULL) //Check if carriage return in string
*p = '\0'; //Replace carriage return with NULL
p = buf; //Set pointer back to input for others to access
return *p;
} else {
p = buf;
p[0] = "\0";
return "\0"; //Return NULL if input fails
}
}
謝謝。
toupper
的返回值是另一個字符,而不是指向字符串的指針。 因此,您正在嘗試訪問內存地址131,這就是為什么您遇到段錯誤的原因。 由於您只對一個字符感興趣,因此可以將違規行替換為:
if (toupper(user_input(2)) == 'Y') {
printf("You said yes\n");
}
請注意,在比較中, Y
用單引號引起來,表示您正在處理字符值(與用雙引號表示字符串值相反)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.