0
votes

I'm having a problem in reversing a string using a function. Here is my code:

#include<stdio.h>

int str_length(char lang);

int main()
{
    char language[100];

    int string_length;

    while(1==scanf("%[^\n]", language))
    {
        string_length=str_length(language);
    }

    int i;

    for(i=string_length; i>=0; i--)
    {
        printf("%c\n", language[i]);
    }

    return 0;
}

int str_length(char lang)
{
    int i;

    for(i=0; lang[i]!='\0'; i++)
    {
        i++;
    }

    return i;
}

The error which is same as the title shows in the line 'for(i=0; lang[i]!='\0'; i++)'.

Please help me to understand the problem.

2
language is declared as an array of characters, but the prototype/signature for str_length() says it is expecting a single char. Perhaps you meant: str_length( char * lang ); <-- note the addition of the * - user3629249
the function str_length() has the variable i being incremented by the for() statement AND with the body of the for() loop, so the returned value will be (approx) twice the actual length of the string. suggest writing: for( i=0; lang[i]; i++ ); Note that the second parameter is simply true (non zero) or false (0) which is all that is needed - user3629249
regarding: while(1==scanf("%[^\n]", language)) when using %[^\n] always include a MAX CHARACTERS modifier (that is one less than the length of the input buffer) to assure that the input buffer is not overrun. Such overrun results in undefined behavior and can/ will lead to a seg fault event. Suggest: while(1==scanf("%99[^\n]", language)) - user3629249

2 Answers

2
votes

Your function str_length() is expecting an char as argument but you are passing it a char * (a pointer which points at a string) in the call. so, you must use pointer notation or array in your function argument. Like

int str_length(char lang[])
{
   //code
}

or

int str_length(char *lang)
{
    //code
}
0
votes

You need to change the function definition as

int str_length(char lang)
...

to

int str_length(char *lang)

The problem is lang is char variable so it cannot be accessed like lang[i]. You intend to have it as array or pointer.