I have to create a function (trim function) who can perform this task: taking a null terminated string and if at the 0-th position of the string there's a whitespace, remove that whitespace. Same thing if the whitespace is at the end of the string (before the zero terminator). Therefore, basically the function ignores the whitespaces in the middle of the string.
Here is what I tried to do so far, (1) I passed " a b " string to trim function. (2) (null pointer check). (3) I took the length of the string by using strlen function.
(4) (this is the delicate part, because debugging line-by-line I found a strange error inside the for loop).
the error is this: when debugger runs the first line of the for loop, it goes inside the loop as expected; okay, that's fine, but when the debugger runs the if check, it should be true (because at the beginning of the string there's a whitespace) and the function is supposed to go in the if body, in the first if statement, and reallocate the memory. But that's not true, because realloc is never executed. Why?
(the function must return the pointer to the reallocated memory).
another error is that "s" isn't initialized but I used it anyway, and that's not true because I initialized s with " a b " string.
char* trim(const char* s) {
if (s == NULL) {
return NULL;
}
size_t length = strlen(s);
for (unsigned int i = 0; s[i] != '\0'; i++) {
if (s[i] == " ") {
realloc(s, length - sizeof(char));
}
}
return s;
}
int main(void) {
trim(" a b ");
return 0;
}