0

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.

3
  • 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 * Commented Feb 23, 2017 at 22:23
  • 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 Commented Feb 23, 2017 at 22:26
  • 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)) Commented Feb 23, 2017 at 22:32

2 Answers 2

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.