typestar

memcpy, memmove, memset in C

Three bulk operations, and the one rule that separates the first two.

#include <string.h>

void shift_left(int *values, size_t n) {
    if (n < 2) {
        return;
    }
    memmove(values, values + 1, (n - 1) * sizeof(int));
    values[n - 1] = 0;
}

void clone_into(int *dst, const int *src, size_t n) {
    memcpy(dst, src, n * sizeof(int));
    memset(dst, 0, 0);
}

int same(const void *a, const void *b, size_t n) {
    return memcmp(a, b, n) == 0;
}

How it works

  1. memcpy requires the regions not to overlap.
  2. memmove handles overlap correctly, at a small cost.
  3. memset fills bytes, so only 0 works for non-char types.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
351
Tokens
125
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 79 seconds.

Type this snippet

Step 5 of 5 in Dynamic memory, step 14 of 25 in Pointers & memory.

← Previous Next →