The sprintf
command has the following declaration:
sprintf(char *str, const char *format, ...);
your declaration in question is:
sprintf(buffer+(p-str), "%s%s", rep, p+strlen(orig));
The sprintf command writes to the character pointer str
, the values rep
and p+strlen(orig)
in accordance with the format string "%s%s"
. Essentially, it is simply combining (or concatenating) rep
and p+strlen(orig)
in buffer+(p-str)
.
Note that str
(in the sprintf declaration
) is of type char *
meaning that buffer+(p-str)
must also be type char *
(a character pointer). buffer
has a pointer address, say 1000
as an example. To that address, we will add the difference p-str
(say 25). So the sprintf
command will combine the two strings rep
and p+strlen(orig)
in memory beginning at the address 1000 + 25 = 1025
We also know from the format string "%s%s"
that both rep
and p+strlen(orig)
will likewise be type char *
pointers. The address of rep
is whatever it is, but the next char *
pointer p+strlen(orig)
will be p
(say 1500) + strlen(orig)
(the length of orig
assume is 20 chars
. So sprintf
will read the string value beginning at address 1520
along with the string rep
into buffer
at address buffer+(p-str)
(or 1025 for this example).
Lets say the pointers point to the following strings:
rep = "In the beginning"
p = "the sky was blue and there was light!"
Lets also say that strlen(orig) = 20
p+strlen(orig) = p[20] = " there was light!"
So the resulting string in buffer at (my fake address 1025) is:
buffer+(p-str) = "In the beginning there was light!"
1
solved Replacing sub-string of a String with another String in c