c - puts函数反转后不打印字符串
问题描述
#include<stdio.h>
void strrevud(char * str , char* rev_str ){
int i=0,j=0;
while(str[i]!='\0')
i++;
for(j=0 ; j<=i ;j++)
*(rev_str + j) = *(str + (i-j));
}
int main(){
char a[50],b[60];
gets(a);
strrevud(a,b);
printf("\n Reversed string is ");
puts(b);
return 0;
}
strrevud
是一个反转字符串的函数。它将两个字符串的地址作为参数。如果我在其中打印 rev_str,strrevud
则会打印,但未main
显示。
解决方案
您的strrevud
函数将反转整个字符串数据,包括终止空字符。因此,终止的空字符将到达第一个元素,因此结果将是一个零字符的字符串。
您必须单独处理终止的空字符。
您也不应该使用gets()
,它具有不可避免的缓冲区溢出风险,在 C99 中已弃用并从 C11 中删除。
#include<stdio.h>
#include<string.h>
void strrevud(char * str , char* rev_str ){
int i=0,j=0;
while(str[i]!='\0')
i++;
/* reverse the string data without terminating null-character */
for(j=0 ; j<i ;j++)
*(rev_str + j) = *(str + (i-1-j));
/* add a terminating null-character */
*(rev_str + i) = '\0';
}
int main(){
char a[51],b[60]; /* allocate one more for a to allow a newline character to be stored */
fgets(a,sizeof(a),stdin);
strtok(a,"\n"); /* remove newline character */
strrevud(a,b);
printf("\n Reversed string is ");
puts(b);
return 0;
}
推荐阅读
- codeigniter - 表达式引擎 2 中的电子邮件消息中的换行符
- light-4j - 如何在 light-4j 中自定义 JWT 验证
- python - Python - 我可以使用 lambda 函数通过 tkinter 生成重复的 GUI 吗?(标签/文本/按钮)
- linux - root 在用户的 bash_history 中看不到 HISTTIMEFORMAT
- cmake - 代码生成器生成自己的 CMake 文件和目标
- azure - VNet 对等网络的强制隧道
- java - 在 Java 中使用正则表达式替换 yyyy-MM-dd 模式末尾的特定符号
- apache-spark - Spark迭代/递归算法 - 打破火花谱系
- python - 将upload_file 发送到电子邮件
- google-cloud-functions - firebase 服务功能未启动