0

我编写了一个程序来使用重复字符的计数来压缩字符串。如果压缩后的字符串比原始字符串长,那么我们仍然返回原始字符串。下面是我的程序:

void stringCompress(char* src) {
    char* original;
    original = src;
    char* rst;
    rst = src;

    int histogram[256];
    for (int i = 0; i < 256; i++) {
        histogram[i] = 0;
    }
    int length = 0;
    while (*src != NULL) {
        length++;
        src++;
    }
    src = original;
    int j = 0;

    for (int i = 0; i < length; i++) {

        histogram[(int) src[i]]++;
        if (histogram[(int) src[i]] == 1) {
            rst[j] = src[i];

            j++;

        }

    }
    rst[j] = '\0';

    char* final;

    rst = original;
    int index = 0;
    char buffer[33];

    for (int i = 0; i < j; i++) {

        final[index] = rst[i];

        stringstream number;
        number<<histogram[(int)rst[i]];
------->        //cout<<number.str()<<endl;
        char* temp = new char[number.str().length()+1];
        strcpy(temp, number.str().c_str());
        index++;
        cout<<temp<<endl;
        for(int k =0 ;k<number.str().length();k++)
        {
            final[index]=temp[k];
            index++;

        }

    }

    final[index] = '\0';
    src = original;

    if (index <= length) {
        for (int i = 0; i < index; i++)

            cout<<final[i];
    } else {
        cout << src << endl;
    }

}

但奇怪的是,如果我把 cout 句子cout<<number.str()<<endl;留在那里(箭头指向句子),那么输出是正确的。例如,aaaabcdaa 输出 a6b1c1d1,aabcd 输出 aabcd。但是,如果我注释掉cout<<number.str()<<endl;,则不会生成任何内容。任何帮助表示赞赏。

4

1 回答 1

2

该变量final在您的代码中未初始化。当我使用内存缓冲区对其进行初始化时,无论您指向的行是否被注释掉,您的程序都会打印所需的输出。

也许您打算使用buffer(未使用的)作为内存final,例如:

final = buffer;
于 2012-07-15T20:01:25.490 回答