#include<stdio.h>

void reverse(char str[]);

int main()
{
    char str[100];
    int i;

    printf("Enter to reverse : ");
    scanf("%s",str);
    reverse(str);
    return(0);
}
/* Function */

void reverse(char str[])
{

    int i;
    for(i=99;i>=0;i--)
    {
        printf("%c",str[i]);
    }
    putchar('\n');
}

Why there is a runtime error in the above programme..........

help!!!!!!
URJENT!!!!!!!!

Recommended Answers

All 2 Replies

Try zeroing str[] or declaring it as global...Plus please use fgets() instead of scanf()...Like below

#include<stdio.h>

char str[100];

void reverse(char str[]);

int main()
{
    int i;

    printf("Enter to reverse : ");
    fgets(str, 100, stdin);
    reverse(str);
    return(0);
}
/* Function */

void reverse(char str[])
{

    int i;
    for(i=99;i>=0;i--)
    {
        printf("%c",str[i]);
    }
    putchar('\n');
}
commented: making it global is not the answer -1

do not make it global. that is not good advice, and doesnt fix the root of your problem.

i do agree that you need to use fgets(), instead of scanf(), because scanf() should never be used to input strings. scanf will not accept anything further once you pass in a whitespace.

your real problem here is that in your string size of 100 characters, everything beyond the end of the input string is garbage, and your reverse function is attempting to print all that garbage.

say you enter the string (using fgets!) that reads "hello how are you". this gives a string of length 18 characters: the 17 characters and spaces, plus the newline character. (note that you would need a char[] array of 19 to hold it because of the guaranteed terminating Null character.)

the remaining 81 characters is random garbage. you do not want to print those, you only want to print the first 17 characters that are valid.

do something like this in your "reverse()" function:

length = strlen(str);
    if (str[length-1] == '\n')
    {
        str[length-1] = '\0';
        length--;
    }
    for(i=length-1;i>=0;i--)
    {
        printf("%c",str[i]);
    }

Note: "strlen()" requires that you include the <string.h> library.

.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.