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.
charis a character type, not a string type.charrepresents 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 likestrcat, string-wise I/O functions such assprintf, or manually manipulate the individual bytes in a string.snprintfreturns anint, 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-1on 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.