问题描述
代码如下。它编译时没有警告或错误,但终端上没有打印任何内容。任何想法为什么?
我想答案一定很明显了,我看不到。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* palindrome (char *word);
main()
{
char *leksi,*inverse_leksi;
//leksi means word
leksi = malloc(sizeof(char)*256);
inverse_leksi = malloc(sizeof(char)*256);
gets(leksi);
inverse_leksi = palindrome(leksi);
puts(inverse_leksi);
}
char* palindrome (char *word)
{
int i;
char *inverse_word;
inverse_word = malloc(sizeof(char)*256);
for (i = 0; i < strlen(word) + 1; i++)
{
inverse_word[i] = word[strlen(word) - i];
}
return inverse_word;
}
解决方法
有效的 c 样式字符串中的字符位于索引 0
到 strlen(var) - 1
中。索引 strlen(var)
中的字符是空终止符 (\0
)。在循环中,您将此字符分配给 invers_word[0]
,因此您将返回一个空字符串。相反,您应该少迭代一个字符,然后显式处理空终止符字符串。此外,您在索引计算中有一个逐一错误:
// iterate up to the length of the string,without the \0
for (i = 0; i < strlen(word); i++)
{
inverse_word[i] = word[strlen(word) - i - 1];
}
inverse_word[strlen(word)] = '\0'; // explicitly handle \0
,
使用这个:inverse_word[i] = word[strlen(word) - i - 1];
。如果您没有 -1
,则要复制的第一个字符将是 \0
。
不要使用gets
。有更好的选择。