c - strcmp() 函数未提供预期输出
问题描述
我是 C 新手。该程序是反转一个字符串,检查它是否是回文并打印反转的字符串。尽管即使在输出中(输出在代码下方),反转的字符串与原始字符串相同,但 strcmp() 函数给出了错误的输出。
#include<stdio.h>
#include<string.h>
int main()
{
int n;
scanf("%d",&n);
char ch[n];
scanf("%s",&ch);
n=strlen(ch);
char temp[n];
int k=0;
for(int i=n-1;i>=0;i--)
{
temp[k]=ch[i];
k+=1;
}
int l=strcmp(ch,temp);
printf("%d\n",l);
if(l==0)
printf("PALINDROME\n");
else
printf("NOT PALINDROME\n");
for(int i=0;i<n;i++)
printf("%c",temp[i]);
return 0;
}
输出 1
6
nitin
1
NOT PALINDROME
nitin
输出 2
100
nitin
1
NOT PALINDROME
►p@PduV⌡ uVP8a■╚ ■ ☺Σ┼uT╠└a ╠a■ä☺a■╨@↕α@↕αè9Å¥uVP½uZFuVP╬a■░nitin
解决方案
对于初学者而不是
scanf("%s",&ch);
^^^
你必须写
scanf("%s",ch);
该数组temp
不包含字符串。所以这个电话strcmp
int l=strcmp(ch,temp);
调用未定义的行为。
您需要在 for 循环之后附加temp
带有终止零字符的数组,例如'\0'
temp[k] = '\0';
为此,您需要像这样声明数组
n=strlen(ch);
char temp[n + 1];
推荐阅读
- sql - 分析零件的流入和流出
- macros - 如何避免defmacro中的eval?
- javafx - Raspbian Stretch Javafx“无法打开显示”
- jpa - JPA 事务未启动...如何解决?
- android - 仅允许 Android 访问 Firestore 数据库
- html - Angular - 无法连接 HTML 页面中的值
- android - 调用 onPause 后重新启动活动
- javascript - 如何避免 jquery ajax 错误消息打印到控制台
- kotlin - 从 java 类中检索 kotlin 注释
- jquery - 有没有办法在下拉列表中获取非选定项目的值?