Hi all,
is it possible to write a function named memcat, which offers
functionality similar to that of the strcat fn, i.e i mean a function
on the following lines:-
void * memcat(void *s1, void *s2);
now s1 should point to the beginning of the concatenated memory
region. now as in strcat how to determine the terminating memory
location...???
Let's begin with the last question: How to determine
the end. Two ends, really, because you need to find the
end of the existing piece that begins at s1 and the end
of the added piece that begins at s2. The other memxxx
function (memset, memchr, ...) use byte counts for this:
the caller provides an extra argument giving the number
of bytes in the memory area. For memcat there are two
memory areas, hence two counts, and the function looks like
void *memcat(void *s1, size_t n1, void *s2, size_t n2);
Let's not stop there, though. Think for a minute about
what memcat will do, internally. All the area 1 bytes will
remain as they are, untouched, and the new material will be
added right after them. So memcat probably begins with
void *target = (char*)s1 + n1;
.... to get a pointer the the spot where the new material
will go. (The (char*) cast is needed because you can't do
arithmetic on a void* pointer.) What next? The rest of the
job is just copying the area 2 material to its new position.
So the complete implementation of memcat might look like
void *memcat(void *s1, size_t n1, void *s2, size_t n2) {
void *target = (char*)s1 + n1;
memcpy(target, s2, n2);
return s1;
}
.... or, with some abbreviation
void *memcat(void *s1, size_t n1, void *s2, size_t n2) {
memcpy((char*)s1 + n1, s2, n2);
return s1;
}
(An "industrial-strength" version would probably use const
on s2, and a version for C99 compilers would also use the
restrict qualifier, but the outline would be the same.)
In other words, memcat is just memcpy with a different
starting point! And that's probably why it doesn't exist in
the Standard library: it's a trivial variation on a function
that's already provided. Adding it would be a little bit like
adding a sqrt_half function that computed the square root of
one-half its argument: A task that's easily done by calling
the usual sqrt function with a halved argument to begin with.