char a[50];
int *m, i, j;
gets(a); // 危險!gets 不檢查邊界,C11 已移除
m = a; // 錯誤:int* 指向 char 數組,類型不匹配
for (i=0, j=strlen(a)-1; i
核心問題:int* m 導致指針算術錯誤(按 4 字節步進),gets 不安全,Yes 打印位置錯誤。
#include <stdio.h>
#include <string.h>
#include <ctype.h>
bool is_palindrome(const char* s) {
const char *l = s, *r = s + strlen(s) - 1;
while (l < r) {
if (!isalnum(*l)) { l++; continue; } // 跳過非字母數字
if (!isalnum(*r)) { r--; continue; }
if (tolower(*l) != tolower(*r)) return false;
l++; r--;
}
return true;
}
int main() {
char buf[1024];
if (fgets(buf, sizeof(buf), stdin)) {
buf[strcspn(buf, "\n")] = '\0'; // 去除換行
puts(is_palindrome(buf) ? "Yes" : "No");
}
return 0;
}
字符串: 1 2 3 2 1
索引: 0 1 2 3 4
↑ ↑
l r
比較 *l == *r → 移動 l++, r-- → 相遇/交叉停止
// 形參用 const char* 防止誤修改,返回 int 兼容 C89
int check_palindrome(const char* str) {
const char *left = str, *right = str + strlen(str) - 1;
while (left < right) {
if (*left != *right) return 0;
left++; right--;
}
return 1;
}
// 調用
char input[100];
fgets(input, sizeof(input), stdin);
input[strcspn(input, "\n")] = '\0';
printf("%s\n", check_palindrome(input) ? "Yes" : "No");
gets / scanf("%s") 無長度限制;int* 訪問 char[]);fgets + 去換行;const;