2 ms·
I see what you're trying to do, but it won't work this way. Since your termination condition is z_terminated[index], you must never look beyond index, yet you a
by anatoly 16y ago
I see what you're trying to do, but it won't work this way. Since your termination condition is z_terminated[index], you must never look beyond index, yet you access [index+write]. This alone means the code's buggy. The second version is similarly flawed.
Note that your code instantly becomes much easier to understand if you rename the variable 'write' to 'gap'.
- dkersten 16y agoEhh, good point. :-/ The second version is identical to the first, except that it ises the z_terminated pointer instead of a separate index. void condense_by_removing(char* z_terminated, char char_to_remove) { int gap = 0; for (; *(z_terminated + gap); ++z_terminated) { if (*(z_terminated + gap) == char_to_remove) { ++gap; } if (gap > 0) { *z_terminated = *(z_terminated + gap); } } *z_terminated = 0; } Interestingly enough, if I try to remove the common *(z_terminated + gap) expression (which a good compiler should do for me..), I end up with a two pointer version similar to yours.
- RiderOfGiraffes 16y agoHave you sent it in? You should ...
- dkersten 16y agoI missed your post the first time around and only did that today, so I assumed it was too late to send in.
- deleted 16y ago[deleted]
- dkersten 16y agoReplacing the 3 additions of gapin the loop with a single subtraction (and an increment): void condense_by_removing(char* z_terminated, char char_to_remove) { int offset = 0; for (; *z_terminated; ++z_terminated) { if (*z_terminated == char_to_remove) { ++offset; ++z_terminated; } if (offset > 0) *(z_terminated - offset) = *z_terminated; } *(z_terminated - offset) = 0; }