首页 > 解决方案 > 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显示。

标签: c

解决方案


您的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;
}

推荐阅读