代码报array subscript is of type 'char'警告,寻求解决方法
你的代码可正常运行,但触发了4处array subscript is of type 'char' [-Wchar-subscripts]编译警告,具体位置如下:
A32.c:42:13: warning: array subscript is of type 'char' [-Wchar-subscripts]
table[pattern[i]] = m - 1 - i;
^~~~~~~~~~~A32.c:55:18: warning: array subscript is of type 'char' [-Wchar-subscripts]
i += table[text[i]];
^~~~~~~~
A32.c:74:13: warning: array subscript is of type 'char' [-Wchar-subscripts]
table[pattern[i]] = m - 1 - i;
^~~~~~~~~~~
A32.c:88:22: warning: array subscript is of type 'char' [-Wchar-subscripts]
i += table[text[i]];
警告原因
C语言中char类型默认是有符号的(取决于编译器),当字符的ASCII值大于127时,会被解析为负数。数组下标要求是非负整数,负数下标会导致未定义行为,因此编译器触发警告提醒风险。
通用修改方案
将所有作为数组下标的char值强制转换为unsigned char,确保下标始终处于0-255的合法范围(匹配你定义的256长度的shift table)。
需要修改的4处代码行:
table[pattern[i]]→table[(unsigned char)pattern[i]]table[text[i]]→table[(unsigned char)text[i]]table[pattern[i]]→table[(unsigned char)pattern[i]]table[text[i]]→table[(unsigned char)text[i]]
修改后的完整代码
int horspool_search(char* text, char* pattern) { int n = strlen(text); int m = strlen(pattern); int count = 0; int shifts = 0; // Create a shift table int table[256]; for (int i = 0; i < 256; i++) { table[i] = m; } for (int i = 0; i < m - 1; i++) { table[(unsigned char)pattern[i]] = m - 1 - i; } int i = m - 1; while (i < n) { int j = 0; while (j < m && text[i - j] == pattern[m - 1 - j]) { j++; } shifts++; if (j == m) { count++; } i += table[(unsigned char)text[i]]; } printf("Horspool's algorithm shifts: %d\n", shifts); return count; } // Function to implement the Boyer-Moore algorithm int boyer_moore_search(char* text, char* pattern) { int n = strlen(text); int m = strlen(pattern); int count = 0; int shifts = 0; // Create a shift table int table[256]; for (int i = 0; i < 256; i++) { table[i] = m; } for (int i = 0; i < m - 1; i++) { table[(unsigned char)pattern[i]] = m - 1 - i; } int i = m - 1; while (i < n) { int j = 0; while (j < m && text[i - j] == pattern[m - 1 - j]) { j++; } shifts++; if (j == m) { count++; i += m; } else { i += table[(unsigned char)text[i]]; } } printf("Boyer-Moore algorithm shifts: %d\n", shifts); return count; }
内容的提问来源于stack exchange,提问作者David

