Resizing Memory with realloc in C
Level 4204 keystrokes
Uses realloc to resize dynamically allocated memory while preserving existing data. (Real code should keep the old pointer until realloc is known to have succeeded.)
C code
// Allocate memory for 2 integers1int *arr = (int *)malloc(2 * sizeof(int));// Initialize first two elements2arr[0] = 10; arr[1] = 20;// Grow to 4 ints; old values are kept, but the block may move3arr = (int *)realloc(arr, 4 * sizeof(int));// Fill the two new slots (realloc does not initialize them)4arr[2] = 30; arr[3] = 40;// Print all four elements5for (int i = 0; i < 4; i++) {6 printf("%d ", arr[i]);7}// Free the memory8free(arr);Output
10 20 30 40
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.
;× 10(× 9)× 9=× 7[× 5]× 5*× 5,× 2"× 2+× 2