I new to C. I am reading a find-replace algorithm for C and I am a bit confused what the - & + operators do in this code:
char *replace(char * src, const char * search, const char * replace) {
char * buffer = malloc(4096); //allocate 4096 bytes in memory to new string
char * p; //substring of my search in the src string
int i;
p = strstr(src, search);
if ( NULL == p ) return src; if // 'search' not found on 'src' return src
i = p - src; //index of my substring
strncpy(buffer, src, i); //copy the substring value to buffer
sprintf(buffer + i, "%s%s", replace,
p + strlen(search)); // ???
return buffer;
}
Since
pis a location in your character array (string) andsrcis the start of it,will set
ito the index at whichppoints.For example, consider the following memory layout:
In this case,
p - srcwill give you127 - 123or4, which is the index of thewwithin"Hi, world".This is called pointer arithmetic is covered in
Additive operatorsin the ISO standard (C99 6.5.6/9):It provides a scaled way of working out differences within the same array or with one pointing just beyond the end of the array (all else is undefined).
By that I mean doing pointer arithmetic with (for example) four-byte integers, will give you a difference of one between the addresses of
arr[7]andarr[8], not four as some may think.The
buffer + iconstruct is simply another way of saying&(buffer[i]), the address of theith element of the arraybuffer. I actually prefer the latter method since it seems more explicit in what I’m trying to represent.For what it’s worth, that’s not actually a very good string replacement code. It has numerous problems:
buffer.mallochasn’t failed.srcsearchandreplace.sprintf ("%*.*s%s%s", i, i, src, replace, &(src[i + strlen (search)]));or astrcpyand twostrcatoperations. Mixing the two seems incongruous to me.