2017-03-17 2 views
0

Le but de cette fonction est de créer une concat de chaîne avec son palindrome. Par exemple abc -> abccbaUne chaîne et son palindrome

Voici mon code, et le résultat affiche toujours la chaîne d'origine sans aucune modification. J'ai réservé quelques espaces pour la corde et son palindrome, mais ça ne marche toujours pas.

char *mirror(const char *str) { 
    char *result = malloc(2 * strlen(str) * sizeof(char)); 
    int str_len = strlen(str); 
    for (int i = 0; i < str_len; ++i) { 
     result[i] = str[i]; 
    } 
    for (int j = str_len; j < 2*str_len; ++j) { 
     result[j] = str[2*str_len-j]; 
    } 
    return result; 
} 

Répondre

0

Code n'allouer et ajouter un caractère nul .

Mieux vaut utiliser size_t pour l'indexation et le dimensionnement de la baie.

Vérifier l'allocation a échoué

char *mirror(const char *str) { 
    size_t length = strlen(str); 
    char *result = malloc(2*length + 1); // + 1 for \0 
    if (result) { 

     size_t r; 
     for (r = 0; r < length; ++r) { 
     result[r] = str[r]; 
     } 

     size_t j = length; 
     for (; r < length*2; ++r) { 
     result[r] = str[--j]; 
     } 

     result[r] = '\0'; 
    } 
    return result; 
}