Sizeof Operator in C
Level 5327 keystrokes
Prints sizeof for char, int, a struct with padding, an int array and a pointer, and divides sizeof(arr) by sizeof(arr[0]) to count the elements. On a typical 64-bit system it prints 1, 4, 12, 40, 8 and 10.
C code
// Its members add up to 6 bytes, but alignment adds padding1struct Aligned { // 1 byte at offset 02 char a; // 4 bytes; 3 padding bytes after a put it at offset 43 int b; // 1 byte at offset 8, then 3 padding bytes so the size is a multiple of 44 char c;5};6 // An array of 10 ints7int arr[10];// A pointer to the first element; it no longer knows the array length8int *ptr = arr;9 // sizeof(char) is 1 by definition10printf("char: %lu\n", sizeof(char));// int is typically 4 bytes11printf("int: %lu\n", sizeof(int));// Includes the padding: typically 12, not 612printf("struct: %lu\n", sizeof(struct Aligned));// For a real array, sizeof is the whole array: 10 * 4 = 4013printf("array: %lu\n", sizeof(arr));// Only the pointer itself: 8 bytes on 64-bit systems14printf("pointer: %lu\n", sizeof(ptr));// Total size / element size gives the element count: 40 / 4 = 1015printf("elements: %lu\n", sizeof(arr) / sizeof(arr[0]));Output
char: 1 int: 4 struct: 12 array: 40 pointer: 8 elements: 10
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.
(× 13)× 13;× 12"× 12,× 6:× 6\× 6%× 6[× 2]× 2