You should use algorithms for this, as they are well tested. But if you want to analyze your code and understand the failure consider a high level description of what your code is running (See Tony's answer).
You maintain two indices into the buffer, one for reading and one for writing. Whenever the reading head detects a space you move it but skip the write. If the character is not a space you use the read head to get a value and write it through the write head.
In your implementation the read head is ptr+i
, which is spelled a bit strange as an offset from the write head (as in ptr[i]
). The write head is ptr
(*ptr =
). But your test in the loop is using the write head instead of the read head: if (*ptr==' ')
.
Even if you fix this, the implementation has other issues, like for example the fact that if there are two consecutive spaces, since you do a single test in the loop. A rewrite of your algorithm could be:
char* remove_spaces(char* buffer) {
char *read = buffer;
for (char *read = buffer; (*read), ++read) {
if (*read != ' ') { // copy element
*buffer = *read;
++buffer; // and increment write head
}
}
*buffer = 0; // ensure null termination
return read;
}
Now, the algorithm can be further improved (performance) by removing the number of writes to memory if you do an initial search for the first space and use that as the starting point for the loop above. That will reduce the number of operations and the number of cache lines that are marked dirty.