Iam619
Iam619

Reputation: 795

C++ string compress

I wrote a program to compress a string using the counts of repeated characters. if the compressed string is longer than the original string, then we still return the original string. Below is my program:

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;
    }

}

But strange thing is that if I leave the cout sentence cout<<number.str()<<endl; there (the arrow points to the sentence), then the output is right. For example, aaaabcdaa outputs a6b1c1d1 and aabcd outputs aabcd. However if I comment out cout<<number.str()<<endl;, then nothing is generated. Any help is appreciated.

Upvotes: 0

Views: 1865

Answers (1)

R&#252;diger Hanke
R&#252;diger Hanke

Reputation: 6255

The variable final is uninitialized in your code. When I initialize it with a memory buffer, then your program prints the desired output whether the line you pointed to is commented out or not.

Perhaps you meant to use buffer (which is unused) as memory for final, such as:

final = buffer;

Upvotes: 2

Related Questions