Originally Posted by
iMalc
That code you've posted fails to nul-terminate the string afterwards. It will work provided that there are nuls in the rest of the buffer, but this code should not rely on that.
The only problem I can see with that code is the case were a space is before the null character:
Code:
#include <stdio.h>
int main(void)
{
char string[] = "a b c \0xxxx";
int i;
printf(">%s<\n", string);
for (i = 0; string[i] != '\0'; i++)
{
printf("%d - %c\n", i, string[i]);
if (string[i] == ' ')
{
string[i] = string[i + 1];
string[i + 1] = ' ';
i++;
printf("%d - %c\n", i, string[i]);
}
}
printf("\n>%s<\n", string);
return 0;
}
Then i will be out of bounds.
But according to the assignment in post #1 the input has to be cleaned (removing leading and trailing spaces and redundant spaces in between). Thus adding
Code:
string = clean_input(string);
at the beginning of the function makes it save.
Bye, Andreas