Я пытаюсь перевернуть предложение, не меняя порядок слов,
Например: "Hello World" => "olleH dlroW"
Вот мой код:
#include <stdio.h>
#include <string.h>
char * reverseWords(const char *text);
char * reverseWord(char *word);
int main () {
char *text = "Hello World";
char *result = reverseWords(text);
char *expected_result = "olleH dlroW";
printf("%s == %s\n", result, expected_result);
printf("%d\n", strcmp(result, expected_result));
return 0;
}
char *
reverseWords (const char *text) {
// This function takes a string and reverses it words.
int i, j;
size_t len = strlen(text);
size_t text_size = len * sizeof(char);
// output containst the output or the result
char *output;
// temp_word is a temporary variable,
// it contains each word and it will be
// empty after each space.
char *temp_word;
// temp_char is a temporary variable,
// it contains the current character
// within the for loop below.
char temp_char;
// allocating memory for output.
output = (char *) malloc (text_size + 1);
for(i = 0; i < len; i++) {
// if the text[i] is space, just append it
if (text[i] == ' ') {
output[i] = ' ';
}
// if the text[i] is NULL, just get out of the loop
if (text[i] == '\0') {
break;
}
// allocate memory for the temp_word
temp_word = (char *) malloc (text_size + 1);
// set j to 0, so we can iterate only on the word
j = 0;
// while text[i + j] is not space or NULL, continue the loop
while((text[i + j] != ' ') && (text[i + j] != '\0')) {
// assign and cast test[i+j] to temp_char as a character,
// (it reads it as string by default)
temp_char = (char) text[i+j];
// concat temp_char to the temp_word
strcat(temp_word, &temp_char); // <= PROBLEM
// add one to j
j++;
}
// after the loop, concat the reversed version
// of the word to the output
strcat(output, reverseWord(temp_word));
// if text[i+j] is space, concat space to the output
if (text[i+j] == ' ')
strcat(output, " ");
// free the memory allocated for the temp_word
free(temp_word);
// add j to i, so u can skip
// the character that already read.
i += j;
}
return output;
}
char *
reverseWord (char *word) {
int i, j;
size_t len = strlen(word);
char *output;
output = (char *) malloc (len + 1);
j = 0;
for(i = (len - 1); i >= 0; i--) {
output[j++] = word[i];
}
return output;
}
Проблема в строке, которую я пометил <= PROBLEM
. На первом слове, которое в данном случае «Привет», все работает нормально.
Во втором слове, которое в данном случае «Мир», оно добавляет ненужные символы к temp_word
, я проверил его с gdb
, temp_char
не содержит ненужных, но когда strcat
запускается, последний символ, добавленный к temp_word
, будет чем-то как W\006
,
Он добавляет \006
ко всем символам во втором слове,
Вывод, который я вижу на терминале, в порядке, но печать strcmp
и сравнение result
с expected_result
возвращает -94
.
- В чем может быть проблема?
- Что за символ
\006
? - Почему
strcat
добавляет его? - Как я могу предотвратить такое поведение?
len + 1
байт... Почему там+1
? Вы используете лишний байт, который выделяете? - person Some programmer dude   schedule 30.12.2019reverseWord
. Когда и где он свободен? - person Some programmer dude   schedule 30.12.2019free
переменная а потом вернуть - person DarkSuniuM   schedule 30.12.2019strtok
и о том, как она может предотвратить утечку памяти. передайте выводstrtok
вашей функции обратного слова, а затем выполните реверсирование на месте, заменяя элементы слова, пока не будет достигнут его конец. Как вы можете использовать вывод C-строки с нулевым завершениемstrtok
, чтобы избежать разделения вашей оперативной памяти с помощьюmalloc
? - person Joel Trauger   schedule 30.12.2019