0

I need to encrypt the algorithm as follows

Algortihm :

Initially encoded string will be empty. Given an String, Each time the middle char of string will be picked, and appened to encoded string. Ie if string is sanji, First n will be picked. EncodedStr will be "n", Remaning message is "saji", "a" will be picked (In case of even letters, left most middle will be picked) EncodedStr will be "na", Remaining message is "sji"."j" will be picked. Encoded Str is "naj", Remaining Msg is "si". "s" will be picked. followed by i.Final encoded str will be "najsi", and reverse follows for decoding.

Here is my code for encoding and decoding:

char * encode(char *str) {
    if (str == NULL)
        return NULL;
    int len = findLen(str);
    int temp = len;
    if (len == 1)
        return str;
    int k = 0;
    int mid = 0,i;
    int repl_chr = 'A';
    char * en = (char*)malloc(sizeof(char)*len);
    while (len > 0){
        mid = len / 2;
        en[k] = str[mid];
        k++;
        for (i = mid; i < len; i++){
            str[i] = str[i + 1];
        }
        len--;

        //memmove(&str[mid], &str[mid + 1], temp - mid);

    }
    printf("%s",en);
    return en;
}
char* decode(char *str) {
    if (str == NULL)
        return NULL;
    int len = findLen(str);
    if (len == 1)
        return str;
    char * en = (char*)malloc(sizeof(char)*len);
    return NULL;
}

int findLen(char *str){
    int i;
    for (i = 0; str[i] != '\0'; i++){}
    return i;
}

I have few bugs in my code.Can anyone help me to fix the bugs?

Barmar
  • 741,623
  • 53
  • 500
  • 612
mike
  • 9
  • 3
    You need to explain the problems you're having, not just say "I have a few bugs in my code". – Barmar Apr 07 '19 at 04:02
  • 3
    What is `findLen()`, why don't you use the standard `strlen()`? – Barmar Apr 07 '19 at 04:02
  • 1
    [don't cast malloc](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Barmar Apr 07 '19 at 04:02
  • 1
    It's not a good idea to sometimes return a new string, and sometimes return the original string. The caller needs to know whether they should free the result or not. So you should always allocate a new string, even if it's just a copy of the original. – Barmar Apr 07 '19 at 04:04
  • 1
    You should allocate `len+1` bytes, to allow space for the null terminator. And you need to add a null terminator to `en`. – Barmar Apr 07 '19 at 04:05
  • 1
    Instead of removing characters from the string, you can simply copy `str[mid]`, then `str[mid-1]`, then `str[mid+1]`, `str[mid-2]`, `str[mid+2]`, etc. until you've copied everything. – Barmar Apr 07 '19 at 04:07

0 Answers0