Categories
c programming tips and tricks

Copying data

Here are three ways of copying data. The first uses the standard C function, memcpy(), which copies n bytes from the src to the dst buffer:

void copy1(void *src, void *dst, int n) {
      memcpy(dst, src, n);
}

Now let’s look at a do-it-yourself alternative to memcpy(). This could be useful if you wanted to do some more processing or checking of the copied data:

void copy2(void *src, void *dst, int n) {
	int i;
	char *p, *q;for (i = 0, p = src, q = dst; i < n; i++) {
		*p++ = *q++;
	}
}

And finally, here is a function that uses 32-bit integers to achieve faster copying. Bear in mind that this may not be faster than the compiler can achieve if it makes optimizations that are particular to the machine architecture. However, it can be useful in a microcontroller where speed is often very important. In this particular example, the code assumes that the data count n is a multiple of 4 since it is dealing with 4-byte integers:

void copy3(void *src, void *dst, int n) {
	int i;
	int *p, *q;
        for (i = 0, p = (int*)src, q = (int*)dst; i < n / 4; i++) {
	        *p++ = *q++;
	}
}

You can find some examples of copying strings using these three functions in the code archive.

Leave a Reply

Your email address will not be published. Required fields are marked *