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 padding
1struct Aligned {
// 1 byte at offset 0
2 char a;
// 4 bytes; 3 padding bytes after a put it at offset 4
3 int b;
// 1 byte at offset 8, then 3 padding bytes so the size is a multiple of 4
4 char c;
5};
6
// An array of 10 ints
7int arr[10];
// A pointer to the first element; it no longer knows the array length
8int *ptr = arr;
9
// sizeof(char) is 1 by definition
10printf("char: %lu\n", sizeof(char));
// int is typically 4 bytes
11printf("int: %lu\n", sizeof(int));
// Includes the padding: typically 12, not 6
12printf("struct: %lu\n", sizeof(struct Aligned));
// For a real array, sizeof is the whole array: 10 * 4 = 40
13printf("array: %lu\n", sizeof(arr));
// Only the pointer itself: 8 bytes on 64-bit systems
14printf("pointer: %lu\n", sizeof(ptr));
// Total size / element size gives the element count: 40 / 4 = 10
15printf("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

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

More C examples at level 5

← C typing practice