单个字符与字符数组比较报错:subscripted value is neither an array nor pointer nor vector
Hey there! Let's break down what's going wrong with your code and get it working properly.
The Root Cause of the Error
Your suffix function uses an outdated, implicit parameter declaration style that's confusing the compiler. When you write:
int suffix ( str, ch)
The compiler defaults both str and ch to int type (an old C quirk you should definitely avoid). So when you try to access str[i], you're trying to subscript an int—which isn't an array, pointer, or vector—hence the error you're seeing.
Other Issues Holding Your Code Back
Before fixing the main error, let's note a few other problems that would prevent your code from behaving as expected:
- The global
cntvariable will keep its value between function calls, which is almost certainly not what you want. - You're mixing
strchrchecks with manual character comparisons, leading to redundant work and missed edge cases. - The function is missing a closing brace, and you didn't show how you intended to call it.
Corrected Code
Here's a fixed version that addresses all these issues:
#include <stdio.h> #include <string.h> // Explicitly type parameters, make cnt local to the function int suffix(const char *str, char ch) { int cnt = 0; int i = 0; // Loop through each character until we hit the string's null terminator while (str[i] != '\0') { if (ch == str[i]) { printf("\n%s\n", str + i); cnt++; } i++; } return cnt; } // Example main function to test the suffix function int main() { char input_str[80]; char target_ch; printf("Enter a string: "); fgets(input_str, sizeof(input_str), stdin); // Remove the newline character added by fgets input_str[strcspn(input_str, "\n")] = '\0'; printf("Enter a character to search for: "); scanf("%c", &target_ch); int result = suffix(input_str, target_ch); printf("\nTotal occurrences found: %d\n", result); return 0; }
Key Fixes Explained
- Explicit Parameter Types: We declared
strasconst char *(since we don't modify the string) andchaschar, so the compiler correctly recognizesstras a pointer (which can be subscripted like an array). - Local
cntVariable: Instead of using a global variable, we declarecntinside the function so it resets to 0 every time the function runs. - Simplified Loop: We replaced the
strchrcheck with a straightforward loop over the string until we hit the null terminator ('\0'), making the logic clearer and avoiding redundant checks. - Added Test
mainFunction: This shows how to properly call thesuffixfunction with user input, including handling the newline character left byfgets.
Why Your Original Comparison Idea Was Correct
You're totally right that a single char and a character array element (also a char) can be directly compared with ==—the problem wasn't the comparison itself, it was the incorrect type of the str parameter that made str[i] invalid.
内容的提问来源于stack exchange,提问作者Tal Mushkin

