Void Pointer in C

Level 4289 keystrokes

Uses void pointer to create a generic function that handles multiple data types.

C code

// void * can hold the address of any type; type says what it really is
1void printValue(void *ptr, char type) {
// A void * cannot be dereferenced: cast to int * first, then use *
2 if (type == 'i') printf("%d\n", *(int *)ptr);
// Cast to float pointer and dereference
3 if (type == 'f') printf("%.2f\n", *(float *)ptr);
// Cast to char pointer and dereference
4 if (type == 'c') printf("%c\n", *(char *)ptr);
5}
// Different types of data
6int i = 42; float f = 3.14; char c = 'X';
// Pass addresses with a type tag: prints 42, 3.14 and X
7printValue(&i, 'i');
8printValue(&f, 'f');
9printValue(&c, 'c');

Output

42
3.14
X
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • '× 14
  • (× 13
  • )× 13
  • ;× 9
  • =× 9
  • ,× 7
  • *× 7
  • "× 6
  • \× 3
  • &× 3

More C examples at level 4

← C typing practice