【发布时间】:2020-04-19 08:52:55
【问题描述】:
我正在尝试颠倒一个句子,而不改变单词的顺序,
例如:“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在那里?你使用你分配的额外字节吗? -
另外请想想你在
reverseWord中分配的内存会发生什么变化。何时何地免费? -
@Someprogrammerdude 实际上我是 C 新手,感谢您指出我需要阅读更多内容,第一个,我不知道,第二个是我关心的问题之一,但是当然我不能
free一个变量然后返回它 -
考虑使用
strtok函数以及它如何防止内存泄漏。将strtok的输出传递给您的反向单词函数,然后通过交换单词的元素直到到达它的末尾来执行就地反转。如何使用strtok的空终止 C 字符串输出来避免使用malloc占用 RAM?