I attempted a problem from the Cracking the Coding Interview book. The following input: aabcccaaa
should give the following output: a2b1c3a3
. Any advice is much appreciated!
#include <stdio.h> #include <stdlib.h> #include <string.h> char* compress(char*); int main(int argc, char** argv) { if(argc==2) { printf("The compression of %s is %s \n", argv[1], compress(argv[1])); } else printf("Not correct number of inputs."); } char* compress(char* str) { const size_t len = strlen(str); char result[len]; //initialized to 0, so length check can be done later memset(result, 0, len); int counter; int j = 0; if(str==NULL || len == 0) return 0; result[0] = str[0]; for(size_t i = 0; i < len; i++) { counter = 1;//reset counter //to make sure no array out of bounds exception occurs if(result[j+1]==0) result[++j] = counter + '0'; else return str; while(str[i] == str[i+1]) { //to store number in char array, add the asci value // of 0. result[j] = (++counter + '0'); i++; } if(result[j+1]==0) result[++j] = str[i+1]; else return str; } result[++j] = '0'; //to avoid "function returns address of local variable" error //to also avoid altering original argument char* str1 = (char*)malloc(sizeof(result)); strcpy(str1, result); return str1; }
result
should belen+1
bytes long (to include the terminating null character)\$\endgroup\$