首页 > 解决方案 > 无法将返回的函数分配给主变量

问题描述

代码如下。它编译时没有警告或错误,但终端上没有打印任何内容。任何想法为什么?

我想答案一定很明显了,我看不到。

#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;
}

标签: cstringreverse

解决方案


0有效 c 样式字符串中的字符位于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

推荐阅读