Search code examples
cfunctioncharc-stringstrim

The code i wrote is supposed to take the string i enter and remove the first letter but it doesnt work


I tried making a program to take a string, remove the first character, then move the rest back one index, but when i compile and run it it just returns the same string.

Here's the code

#include <stdio.h>
#include <string.h>

void remfirst(char arr[]) {
    for(int i = 0;i <= strlen(arr); i++) {
        arr[i] = arr[i+1];
    }
}

int main() {
    char string[32];
    fgets(string, 32, stdin);
    remfirst(&string[32]);
    printf("%s", &string);
    return 0;
}

Solution

  • For starters the argument expression of the function call is incorrect

    remfirst(&string[32]);
    

    It is a pointer to memory beyond the character array.

    You need to write

    remfirst( string );
    

    A similar problem exists in this call

     printf("%s", &string);
    

    The conversion specifier s expects an argument of the type char * but you are passing an argument of the type char ( * ) [32].

    You need to write

    printf("%s", string);
    

    As for the function itself then it is better to use standard function memmove instead of using manually written for loop. For example

    char * remfirst( char s[] )
    {
        memmove( s, s + 1, strlen( s ) );
    
        return s;
    }
    

    Or

    char * remfirst( char s[] )
    {
        return memmove( s, s + 1, strlen( s ) );
    }