typestar

void pointers in C

A void pointer holds any object address, and the cast back is your responsibility.

int int_from(void *slot) {
    return *(int *) slot;
}

void copy_bytes(void *dst, const void *src, size_t n) {
    unsigned char *out = dst;
    const unsigned char *in = src;
    for (size_t i = 0; i < n; i++) {
        out[i] = in[i];
    }
}

double generic_demo(void) {
    double value = 2.5;
    void *anything = &value;
    return *(double *) anything;
}

How it works

  1. Any object pointer converts to void * and back losslessly.
  2. It cannot be dereferenced until cast to a real type.
  3. This is how a generic container carries elements it knows nothing about.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
322
Tokens
103
Three-star pace
95 tpm

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

Type this snippet

Step 1 of 4 in Generic & function pointers, step 6 of 25 in Pointers & memory.

← Previous Next →