carl
carl

Reputation: 623

I've written a code for reverse a string. But in output it is generating some garbage. Why?

Here is my code. For word with more than 3 alphabets in o/p garbage values are generated.

#include<stdio.h>
#include<stdlib.h>

int main(){
    char a[50],b[50];
    gets(a);
    puts(a);
    int len,i,j;
    i=0;
    while(a[i]!='\0'){
       i++;
    }
    printf("Length: %d",i);
    //reverse
    len = i;
    j=len-1;
    for(i=0;i<=len-1;i++){
        printf("\ni=%d j=%d",i,j);
        b[i]=a[j];
        j--;

    }
    printf("\n___REVERSED TEXT___\n");
    puts(b);


}

Upvotes: 1

Views: 44

Answers (2)

Rafael Coelho
Rafael Coelho

Reputation: 166

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

int main(void){
    char a[50],b[50];

    printf("\nWhat is the word?");
    scanf("%s", a); fflush(stdin);
    int j;

    printf("Length: %lu",strlen(a));
    for(j = strlen(a) - 1; j >= 0; j--){
        b[strlen(a) - 1 - j] = a[j];
    }
    printf("\n___REVERSED TEXT___\n");
    printf("\n%s", b);
}
  • use function strlen of string.h to get the size of the string;
  • the for goes from the end to the beginning of string a filling the string b

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

For starters neither declaration from the header <stdlib.h> is used in the program. So this directive

#include<stdlib.h>

may be removed.

According to the C Standard the function main without parameters shall be declared like

int main( void )

The function gets is unsafe and is not supported any more by the C Standard. Instead use function fgets.

When the string stored in the array a is being copied in the array b the terminating zero also should be copied to the end of the resulted string.

The program can look the following way

#include <stdio.h>

#define N   50

int main( void ) 
{
    char a[N], b[N];

    fgets( a, sizeof( a ), stdin );

    size_t length = 0;

    while ( a[length] != '\0' && a[length] != '\n' ) ++length;

    a[length] = '\0';

    puts( a );

    size_t i = 0;

    for ( ; i < length; i++ ) b[i] = a[length - i - 1];
    b[i] = '\0';

    printf("\n___REVERSED TEXT___\n");
    puts( b );

    return 0;
}

Its output might look like

Hello, World!
Hello, World!

___REVERSED TEXT___
!dlroW ,olleH

Upvotes: 2

Related Questions