-1

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;
}
Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
gent9
  • 21
  • 6
  • 1
    `&string[32]`? The valid indexing range is 0-31. But you shouldn't be passing the address of the 31st item either, simply do `string`. The `%s` format specifier expects a `char *`, not a `char (*)[]`. – Harith May 16 '23 at 19:25
  • You're accessing outside the array. Array indexes go from 0 to len-1. Also, if the user types less than 31 characters, the remaining array elements are uninitialized. – Barmar May 16 '23 at 19:25
  • 1
    Side note: `printf("%s", &string);` is not quite correct. It should be `printf("%s", string);`, which is equivalent to `printf("%s", &string[0]);`. When using the `%s` format specifier, you must pass a pointer to the first character of the string, not a pointer to the entire array. Therefore, you are passing a pointer of the wrong type. Most compilers will warn you of this, if you enable warnings. [Why should I always enable compiler warnings?](https://stackoverflow.com/q/57842756/12149471) – Andreas Wenzel May 16 '23 at 19:26
  • Instead of doing all that copying, simply declare a `char *`, initialise it with `&string[1]`, and print it. Or simply pass `string[1]` to `printf()`. – Harith May 16 '23 at 19:28

1 Answers1

1

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 ) );
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335