OK, what do you think of this?
I'm not at all squeemish about criticism as long as it's to help me program better
Code:
int indexOf(char *str1, char *str2)
{ //Is this the best way to do this?
char *ptr2;
int idx;
ptr2 = strstr(str1,str2);
idx = ptr2 - str1;
if(idx < 0) idx = -1;
return idx; //will the memory for idx still be allocated once it is returned?
//Does 'return' pass the allocation on or kill it even though I've returned it?
}
char *strReplaceAll(char *st, char *orig, char *repl)
{
char *buffer = malloc((strlen(st) - srlen(orig)) + strlen(repl) + 1);
char *ch;
char *ptrSt = &st;
if (!(ch = strstr(st, orig))) return st;
strncpy(buffer, st, ch-st);
buffer[ch-st] = 0;
//sprintf automatically moves the 0 to the end after putting the string together??
sprintf(buffer+(ch-st), "%s%s", repl, ch+strlen(orig));
ptrSt = *buffer;
free(buffer); //Did I successfully copy the contents of buffer to the original memory location of txt1
//Does ptrSt (that is, txt1) still contain the contents (in the originally allocated memory space for txt1) that was in buffer?
if ((ch = strstr(st, orig)))
{
ptrSt = strReplaceAll(ptrSt, orig, repl);
}
return ptrSt;
}
int main(int argc, char *argv[])
{
char *txt1 = argv[1];
{
char *txt2 = argv[2];
char *txt3 = argv[3];
int x = indexOf(txt1,txt2);
txt1 = strReplaceAll(txt1, txt2, txt3);
}
//is the memory for argv[2] & argv[3] still allocated?
//Does txt1 still point to the location of the original argv[1] but with a different size & a changed value?
return 0;
}
Well I compiled it and I see that the whole thing with ptrSt doesn't work.
I just cannot figure out how to make the original memory argv[1] change in that function.
All I'm really trying to do is allocate as *little* memory as possible and get that changed value back into main.
How would you gurus write this stuff?