0

I need to write a function that deletes the spaces in the beginning and the end of a string. I tried this, but it's not working and I don't know exactly what I'm doing wrong. Why this code isn't good?

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

void CutSpaces(char str[]){
    char s[] = {};
    for (int i, j = 0; str[i] != '\0'; i++){
        if (str[i] != ' '){
            s[j] = str[i];
            j++;
        } 
        else if ((str[i] == ' ') && (str[i+1] != ' ')) {
            s[j] = str[i];
            j++;
        } 
    }
   printf("%s\n", s); 
}

int main(){
    char str[] = "   hello world   ";
    CutSpaces(str);
    return 0;
}
rqo
  • 1
  • 4
  • With `char s[] = {};` you define an *empty* array. That isn't really allowed by the C standard. Also remember that arrays in C have a fixed size, once defined they can't be extended or change size in any other way. – Some programmer dude Sep 16 '22 at 18:59
  • 1
    Your `s` array is essentially empty. Your initializer may possibly cause it to have a single character, but even if that's the case, it will hardly help. How big did you think `s` was? What do you think the assignment `s[j] = ...` will do? You're corrupting memory. You need to change the declaration for `s` to guarantee that it has as much storage as you need (or change it to a pointer and use `malloc` to allocate storage). – Tom Karzes Sep 16 '22 at 18:59
  • @TomKarzes thank you very much. This exercise was passed before we started to see data structure topics, so I didn't think of this. It makes sense now. – rqo Sep 16 '22 at 19:07

0 Answers0