fuggy concept on how function and character array work in function parameter

50 Views Asked by At

** I understood how the function getline is working, it simply assigning value in each s[] array address which gets stored into the char line[] array because function argument has local scope there is no conflict due to the use of different array names unless it shares the same data type, But my concern is that why checker function has no effect on an actual string. correct me if the above understanding is wrong and why the checker function not working.** the expected result was, getting string without trailing blanks and tabs like (hello World) but instead of that actual input that I typed in is printed which is ('\s'hello World'\t').

#define MAXLINE 50

int getline(char line[], int max);
int checker(char line[]);

int main(){
    char line[MAXLINE];

    while( getline(line, MAXLINE) > 0 )
        if( checker(line) > 0 )
            printf("%s",line);
    return 0;
}


int getline(char s[],int lim){
    int c,i,j;
    j=0;

    for(i=0; (c=getchar()) != EOF && c != '\n';i++){
        if(i < lim-1){
            s[j]=c;
            ++j;
        }
    }
    if(c == '\n'){
        s[j] = c;
        ++j;
        ++i;
    }
    s[j] = '\0';
    return i;
}


int checker(char s[]){
    int i;
    i=0;

    while(s[i] != '\n' )
        ++i;
    --i;
    while(i >= 0 && (s[i] == ' ' || s[i] == '\t') )
        i++;
    if( i >= 0){
        ++i;
        s[i] = '\n';
        ++i;
        s[i] = '\0';
    }
    return i;
}
2

There are 2 best solutions below

0
On

The bug seems to be here:

while(i >= 0 && (s[i] == ' ' || s[i] == '\t') )
    i++;
    ^^^^
    This shall probably be i--;

That said... Your function isn't secure. It lacks some checks to prevent access outside the char array.

For instance:

  • What happens if the input string has no '\n' ?

  • What happens if the input string is a space followed by '\n' ?

Also the getline function has a problem. If the input is longer than lim, the code will do s[lim] = '\0'; which is out of bounds.

1
On

If you are trying to trim trailing blanks and tabs from your string, try changing the contents of the second while loop in checker() to contain i-- rather than i++.

Since checker() is intended to change the string, perhaps a different name would be better. The word check does not usually imply modification. A well chosen name is a great help to the next person who encounters your code.