0

不確定な数の変数とそのカウントのソートされた配列があります。次のような文字列を作成する必要があります。

Attribute[0]: p=2, e=8

私の問題は、配列が実際にはポインターであり、固定長のループを使用したくないため、唯一の解決策は配列ポインターを使用することです。

void printArray(Node_ptr node){
    int count=0; //character count
    char *temp= node->attributes; //duplicate attribute array

    char cur; //current char
    char *outputCat= emalloc(150); //concatenate counts to a single string

    strcpy(outputCat, "Attribute %d counts are: ");
    qsort(temp, lineCount, sizeof(char), compare); //sort the array

    while ((temp) != NULL){
        cur= *temp;
        ++temp;
        if (strcmp(&cur, temp)==0) //if characters are same
            count++; 
        else { //build reporting string
            strcat(outputCat, &cur);
            strcat(outputCat, "= ");
            sprintf(outputCat, "%d  ", count);
            count=0;
        }
    }
    free(outputCat);
}

ここでの問題はstrcmp(&cur, ++temp)==0、デバッガーで値を確認しても、毎回 false を返すことです。このため、else 条件は常に構築されており、何度か繰り返した後に segfault がスローされます。

2 つの質問:

1-strcmp同一の値が入力された場合でも、0 以外の値を返すことができるのは何ですか? 2- コードを修正するにはどうすればよいですか?

4

1 に答える 1

2

あなたの行で:

strcmp(&cur, temp)

curcharローカルで宣言されているため、&curスタック上のある場所にすぎず、このコンテキストでは意味がありません。

cur現在の文字が次の文字と同じかどうかを確認するつもりだと思います*temp
これは次のようになります。

if (cur == *temp) //if characters are same
    count++; 

次に、出力セクションを大幅に簡素化します。

sprintf(outputCat, "%c = %d", *cur, count);  // e.g.   "e = 8"
count=0;

そして最後に、あなたのループが終了することはないと思います. temp++while temp != NULL.
ポインターに格納されている VALUE を確認するつもりだと思いますtemp
*tempNULL ではなく、'\0' に対して適切にチェックする必要があります。
(\0 と NULL はたまたま同じ値を持ちますが、意味的に同じに扱われるべきではありません)

while (*temp != '\0'){

PS あなたのシンプルだが優れたコメント「//文字が同じなら」は、あなたのコードを理解するのに非常に役立ちました. これは、短くて意味のあるコメントがINVALUABLEである優れたケースです。ありがとうございました。


(願わくば最終編集)
全体として、私が推奨する変更は次のようになります。

void printArray(Node_ptr node){
    int count=0; //character count
    char *temp= node->attributes; //duplicate attribute array

    char cur; //current char
    char *outputCat= emalloc(150); //concatenate counts to a single string

    strcpy(outputCat, "Attribute %d counts are: ");
    qsort(temp, lineCount, sizeof(char), compare); //sort the array

    while (*temp != '\0'){
        cur= *temp;
        ++temp;
        if (cur == *temp) //if characters are same
            count++; 
        else { //build reporting string
            sprintf(outputCat, "%c = %d", *cur, count);  // e.g.   "e = 8"
            count=0;
        }
    }
    free(outputCat);
}

それはあなたにとってどのようにうまくいきますか?

于 2011-09-12T00:34:51.787 に答える