I’m studying some basic functions for my C midterm and I realized I copied down my instructor’s example incorrectly. I’m probably just too tired to think this through right now and a little push would be greatly appreciated.
void replace_last(char s[], int oldc, int newc){
size_t i, pos-1; /* I have no idea why I wrote pos-1. I know I need it though */
for(i = 0; s[i] != '\0'; i++){
if(s[i] == oldc)
pos == i;
if(pos != -1)
s[pos] = newc;
}
}
So your copied code had three problems:
pos-1,pos == i, and thirdly, the logicif(pos != -1) s[pos] = newc;needs to be outside the loop.Edit: Just to round-off the answer, the “non-manual” way of doing this would be, for example:
(You could, if you wished, save the return of
strrchr()of in a temporary pointer, to avoid the second call tostrrchr(),but this is probably unnecessary: gcc with-O1does this for you automatically.)