void pointers

Basic types / Pointers

//void * holds an address of any type
int number = 42;
double real = 2.5;

void *p = &number;
//to read the value, cast to the real type
int n = *(int *)p;
//n is 42

p = ℜ
double r = *(double *)p;
//r is 2.5

//malloc returns void * too: C converts it to int * without a cast

//a function for any type takes void * and the size of the value;
//void * has no arithmetic, so the bytes are read through unsigned char *
void swap(void *a, void *b, size_t size) {
    unsigned char *x = a;
    unsigned char *y = b;
    for (size_t i = 0; i < size; i++) {
        unsigned char temp = x[i];
        x[i] = y[i];
        y[i] = temp;
    }
}

int i1 = 1, i2 = 2;
swap(&i1, &i2, sizeof i1);
//i1 is 2, i2 is 1

double d1 = 1.5, d2 = 3.5;
swap(&d1, &d2, sizeof d1);
//d1 is 3.5, d2 is 1.5

printf("n is %d\n", n);
printf("r is %g\n", r);
printf("i1 is %d\n", i1);
printf("i2 is %d\n", i2);
printf("d1 is %g\n", d1);
printf("d2 is %g\n", d2);