2016-09-17 30 views
-1

我的程序是反向的,即使正在生成反向,但問題是還有一個不需要的垃圾值。同時反轉字符串的垃圾值?

我無法理解問題所在。

#include <stdio.h> 
#include<string.h> 
int main() 
{ 
    char ar[100],b[100]; 
    int i,j; 
    scanf("%s",ar); 
    j=strlen(ar); 
    printf("%d",j); 
    j-=1; 
    for(i=0;j>=0;i++)  
    { 
     b[i]=ar[j]; 
     j--; 
    } 
    printf("\n %s",b); 
} 

這是輸出: enter image description here

+2

你必須null-terminated你的輸出字符串。 –

回答

1

您需要在末尾添加

b[i] = 0; 

終止字符串。

1

函數printf()取決於NUL終止字符作爲停止打印的標記,因此您應該使用字符'\ 0'終止您的數組。此外它會更好地作出扭轉字符串的功能:

#include <stdio.h> 
#include <string.h> 

void m_strrev(char *str, char *output); 

int main(void) 
{ 
    char ar[100], b[100]; 
    //int i, j; 
    scanf("%s", ar); 
    /*j = strlen(ar) - 1; 
    for (i = 0; j >= 0; i++) 
    { 
     b[i] = ar[j]; 
     j--; 
    } 
    b[i] = '\0'; 
    printf("%s\n", b);*/ 
    m_strrev(ar, b); 
    printf("%s\n", b); 
} 


void m_strrev(char *str, char *output) 
{ 
    char *e = str; 
    while (*e) { 
     e++; 
    } 
    e--; 
    while (e >= str) { 
     *output++ = *e--; 
    } 
    *output = '\0'; 
}