Reputation: 23
I've been getting the error: "subscripted value is neither an array nor pointer nor vector" for my code on line 14. It seems like it should be able to compare the value in the array to the char since they are both primitive data yet I can't seem to get it right:
#include <stdio.h>
#include <string.h>
char str[80];
char ch;
int cnt =0;
int suffix ( str, ch) {
int i=0;
while (strchr(str+i, ch) != NULL){
if (ch == str[i] ){
printf("\n %s \n", str+i);
cnt += 1;
}
i++;
}
return cnt;
}
int main() {
printf("\n Please type a single character and then press ENTER: \n");
ch = getchar();
printf("\n You have typed in the character \" %c \".\n", ch);
printf("\n Now please enter a string. Press ENTER to confirm: \n");
scanf("%s", str);
printf("\n The String you typed in is: %s.", str);
suffix(str, ch);
printf("The character \" %c \" appeares %d times in the string. \n", ch, cnt);
return 0;
}
Upvotes: 1
Views: 67
Reputation: 13570
The problem is that you are declaring the function like this:
int suffix ( str, ch)
{
...
}
without telling the compiler the type of str
and ch
. So the compiler assumes
they are int
, and you cannot use []
on an int
. You have to declare the
functions like this
int suffix(char *str, char ch)
{
...
}
And why are you declaring str
, ch
and cnt
as global variables? There is
absoulutly no reason for that.
So the program should look like this:
#include <stdio.h>
#include <string.h>
// const char is even better, because you are not modifying the string
int suffix (const char *str, char ch) {
int cnt = 0;
int i=0;
while (strchr(str+i, ch) != NULL){
if (ch == str[i] ){
printf("\n %s \n", str+i);
cnt += 1;
}
i++;
}
return cnt;
}
void clean_stdin(void)
{
int ch;
while((ch = getchar()) != '\n' && ch != EOF);
}
int main() {
int ch;
int cnt;
char str[100];
printf("\n Please type a single character and then press ENTER: \n");
ch = getchar();
printf("\n You have typed in the character \" %c \".\n", ch);
clean_stdin(); // to get rid of the newline in the input buffer
// or if the user typed more than a single character
printf("\n Now please enter a string. Press ENTER to confirm: \n");
scanf("%99s", str);
printf("\n The String you typed in is: %s.", str);
cnt = suffix(str, ch);
printf("The character \" %c \" appeares %d times in the string. \n", ch, cnt);
return 0;
}
Upvotes: 2