-1

ポインターを使用して文字列の一部を別の文字列にコピーしようとしています。カウントを超えても停止しませんが、結果の文字列は正しい場所でコピーを開始します。また、文字列は、結果パラメーターからではなく、ソース文字列からコピーされません

#include <stdio.h>

char *getSub(const char *orig, int start, int count, char *res);

int main(void)
{
    const char orig[] = "one two three";
    char res[] = "123456789012345678";

    printf("%s\n",getSub(orig, 4, 3, res));

    return 0;
}

char *getSub(const char *orig, int start, int count, char *res)
{    
    const char *sCopy = orig;

    while (*orig)
    {
        if (start >= (orig - sCopy)) && (res-sCopy < count))
        {
            *res++ = *orig++;
        }
        else
            *orig++;
    }

    return res;
}
4

3 に答える 3

1

大きな間違いは、2 つの無関係なポインターの差を計算していることです(実際のコードにもres - sCopyあると思いますが、その逆もあると思います)。ポインターの差の計算は、両方のポインターが同じ配列を指している (または配列の末尾を過ぎた) 場合にのみ意味があります。書かれているように、何かがコピーされるかどうかは、2 つの配列の任意の場所に依存します。sourceCopysCopy

        if (start >= (orig - sourceCopy)) && (res-sCopy < c))
        {
            *res++ = *orig++;
        }
        else
            *orig++;

とにかく、コピーされたとしても、コピーされた文字数はカウントされません。

もう 1 つの間違いは、コピーを 0 で終了しないことです。

正しい実装は次のようになります

char *getSub(const char *orig, int start, int count, char *res)
{
    char *from = orig, *to = res;
    // check whether the starting position is within orig
    for( ; start > 0; --start, ++from)
    {
        if (*from == 0)
        {
             res[0] = 0;
             return res;
        }
    }
    // copy up to count characters from from to to
    for( ; count > 0 && *from; --count)
    {
        *to++ = *from++;
    }
    // 0-terminate
    *to = 0;
    // return start of copy, change to return to if end should be returned
    return res;
}
于 2012-07-29T23:23:30.493 に答える
0
#include <string.h>

char *getSub(const char *orig, int start, int count, char *res){
    int i,j,len = strlen(orig), limit = start + count;

    if(res == NULL) return NULL;
    if(start >= len || start < 0 || orig == NULL){
        *res = '\0';
        return res;
    }
    for(j=0,i=start;i<len && i < limit;++i){
        res[j++]=orig[i];
    }
    res[j]='\0';
    return res;
}
于 2012-07-31T12:21:14.180 に答える
0

コードには少なくとも 2 つの問題があります。

  1. res - sCopyそれらは異なるオブジェクトを指しているため、意味がありません。
  2. 宛先文字列を null で終了していません。
于 2012-07-29T23:16:23.493 に答える