1

特定のチーズにたどり着くために検索できるチーズのリストを作成しようとしています。完了したら、それぞれについての情報も追加したいと思います。しかし、コードを実行するたびに、タイトルに示されているエラーが表示されます。これが私のコードです:

#include<stdio.h>
#include<string.h>

int main()
   {    
    char cheeses[][20] = {
        "Cheddar",
        "White Cheddar",
        "Colby Jack",
        "Gouda",
        "Blue Cheese",
        "Gorgonzola",
        "Asiago", 
        "Limburger",
        "Feta",
        "Brie",
     };

         void find_cheese(char search_for)
     {
         int i;
         for (i = 0; i < 5; i++) {
             if (strstr(cheeses[i], search_for))
                 printf("Cheese %i: '%s'\n", i, cheeses[i]);
          }
    }

int main()
    {
        char search_for[20];
        printf("Search for: ");
        fgets(search_for, 20, stdin);
        find_cheese(search_for);
        return 0;
     }
}

なぜこうなった?本で調べましたが、答えが見つからないようです。

4

4 に答える 4

2

strstrの 2 番目の引数は にする必要がありますconst char*。あなたは単一の を渡していますchar

于 2012-10-04T12:30:08.977 に答える
2

strstrchar2 番目の引数としてへのポインターが必要です。

const char * strstr ( const char * str1, const char * str2 );

を渡している間char

于 2012-10-04T12:30:11.470 に答える
0
void find_cheese(char search_for)

should be

void find_cheese(char *search_for)

because it is looking for a string (char *), not a single character.

于 2012-10-04T12:32:47.820 に答える
0

strstr() takes a string (char *) as the second argument. For usage see here.

The problem in your code is you're accepting the passed the array incorrectly:

    void find_cheese(char search_for) //This line is wrong
    {

What you wanted to do was:

    void find_cheese(char search_for[])

EDIT:
Here's what is happening. When you access the array in your main function:

find_cheese(search_for);

What you're actually doing here is passing an address. (When you just access the array search_for you get an address). So when your prototype said it was taking a char the compiler saw the address (4 bytes, looking like an int) and truncated it to fit in a one byte char.

The way you prevent that is by passing the whole "string" (a string in C is a character array). So you can do this by passing search_for as an array, or as a pointer (address to a character array).

void find_cheese(char search_for[])

and

void find_cheese(char *search_for)

Will both work and are equivalent for your needs (passing to strstr())

于 2012-10-04T12:32:51.543 に答える