How to implement RLE in C

116 Views Asked by At

I have recently tried coding RLE in C, I have rewritten the whole thing ~5 times and all of times it just says "" or just null. Here is my latest revision, can anyone help me?

#include <stdio.h>
#include <string.h>
char rle(char src[]) {
    char chr = src[0], res = "";
    int count = 0, len = strlen(src), tmp = 0;
    for (int i; i < len; i++) {
        while (chr == src[i]) {
            count++, i++;

        }
        chr = src[i];
        tmp = i;
    }
    res+=src[tmp] + snprintf(NULL,0,"%d",count);
    return res;
}


int main(int argc, char *argv[]) {
    printf("%s", rle("aaaaa"));
}

Tried comparing current character and next one, didn't work.

1

There are 1 best solutions below

0
Oka On

char is a character type, not a string type. char represents a single character - one byte of information.

A string is really a pointer to the first character of a sequence of bytes, always terminated by a zero-byte. Most commonly typed as a pointer-to-char (char *) or array-of-char (char []).

Strings require space - memory; a buffer. You must allocate this memory in some way - an automatically allocated array, a block of dynamic memory (that must be [re]sized manually), a static pool, etc.

Strings in C cannot be combined with the + operator. You must use string functions like strcat, string-wise I/O functions such as sprintf, or manually manipulate the individual bytes in a string.

snprintf returns an int, not a string. This value represents the number of bytes written to the buffer, or the number of bytes that would have been written, in the event that truncation occurs, or -1 on error.

Here is a basic implementation of RLE to study, but you may want to pick up your C textbook, and re-read the chapters on types and strings.

#include <stdio.h>
#include <string.h>

static int rle(char *dest, size_t length, const char *src)
{
    size_t bytes = 0;

    while (*src) {
        size_t remaining = length - bytes;
        size_t sp = strspn(src, (char []) { *src, 0 });
        int rc = snprintf(dest + bytes, remaining, "%zu%c", sp, *src);

        if (-1 == rc || rc >= remaining)
            return -1;

        bytes += rc;
        src += sp;
    }

    dest[bytes] = 0;

    return 0;
}

int main(void)
{
    char source[] = "aaaaabbbbcccaab";
    char result[64] = { 0 };

    if (0 == rle(result, sizeof result, source))
        puts(result);
    else
        fputs("Result failed (I/O error or buffer too small)\n", stderr);
}
5a4b3c2a1b