c - 无法将返回的函数分配给主变量
问题描述
代码如下。它编译时没有警告或错误,但终端上没有打印任何内容。任何想法为什么?
我想答案一定很明显了,我看不到。
#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;
}
解决方案
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
推荐阅读
- image - 如何将使用 Image Intervention 创建的图像内容上传到 ftp 服务器?
- javascript - 反应路由器useHistory上的无效挂钩调用
- android-studio - 当语言为阿拉伯语时,函数以阿拉伯语而不是英语显示数字
- node.js - 在 express 上发出 POST 请求时如何呈现 EJS 文件?
- reactjs - 传递道具 React (Typescript) .Net core
- python-3.x - 将控制台日志写入 Django 中的文件
- reactjs - React - 无法在尚未安装的组件上调用 setState(scaledrone 应用程序)
- gauge - 谷歌图表速度表值更新
- c++ - 链接器未报告多变量错误 - 可能是什么原因?
- sqlite - 状态管理使用 sqflite 插件为 sqlite 数据库保存数据?