-3

私の課題は、独自のバージョンの strchr を作成することですが、うまくいかないようです。アドバイスをいただければ幸いです。ここにあります:

char *strchr (const char *s, int c) //we are looking for c on the string s
{

    int dog; //This is the index on the string, initialized as 0
    dog = 0;
    int point; //this is the pointer to the location given by the index
    point = &s[dog];
    while ((s[dog] != c) && (s[dog] != '\0')) { //it keeps adding to dog until it stumbles upon either c or '\0'
            dog++;
            }
    if (s[dog]==c) {
            return point; //at this point, if this value is equal to c it returns the pointer to that location
            }
    else {
            return NULL; //if not, this means that c is not on the string
            }
}
4

4 に答える 4

4

You are trying to store an address into point but it's an int-variable. You should do something like this:

char *strchr(char *s, char c) {
    int pos = 0;
    while (s[pos] != c && s[pos] != '\0')
        pos++;
    if (s[pos] == c)
        return &s[pos];
    else
        return NULL;
}

By the way: s should be char * not const char * because your returning an pointer to achar, and that wouldn't be a good style ;) (or return const char *)

于 2012-07-08T21:16:06.137 に答える
4

最初に文字列の先頭に初期化され、それ以降移動されていない「ポイント」を返します。その変数はまったく必要ありませんが、単純に &s[dog] を返すこともできます (ただし、変数名としては、dog よりもわかりやすいものを使用したいと思います)。

実際、次のような単純なもので生き残ることができます。

while (*s != c && *s)
    ++s;

return (*s == c) ? s : NULL; 
于 2012-07-08T21:08:59.140 に答える
0
int point;

これはポインターの宣言ではありません。へのポインターを宣言する方法は次のintとおりです。

int *bla;

あなたの場合&s[dog]は へのポインタであるconst charため、次のように宣言pointします。

 const char *point;

他の人が指摘したように、実際には後で関数でこのポインターを無視しています。

于 2012-07-08T21:06:43.170 に答える
0

ここにあなたのコードで

int point; //this is the pointer to the location given by the index
point = &s[dog];

char へのポインタを に変換しようとしているintときに、

char* point = &s[dog];

あなたが望むものです。これは、関数の戻り値の型からわかるはずです。a を返したいのにchar*int(your variable point) または NULL を返します。実際に を変更することはないためpoint、実際には配列の最初の文字のアドレスを返しているため、コードは意図したとおりに機能しません。これを主張する場合は、使用する方が良いでしょう

char* point = &s[dog];
while ((*point != c) && (*point != '\0')) {          
   ++point;
}
return (*point == c) ? point : NULL;

charしかし、ここでは、 を と比較したいので、まだ概念的な問題があるようですintint配列または配列が必要な場合は解決する必要がありますchar。配列が必要な場合はchar、入力引数cを 型に変更しますchar

于 2012-07-08T21:10:45.487 に答える