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.
languageis declared as an array of characters, but the prototype/signature forstr_length()says it is expecting a single char. Perhaps you meant:str_length( char * lang );<-- note the addition of the*str_length()has the variableibeing incremented by thefor()statement AND with the body of thefor()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 neededwhile(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))