Sub topic 1
Data Types, Sizes, and Addresses
Prerequisites
Assume you know basic C syntax, variables, operators, functions, binary and hexadecimal notation, and how to compile and run a small C program.
A C variable has a type, a value, and a location in memory. The type tells the compiler how many bytes to reserve, how to interpret those bytes, and which operations are valid.
The sizeof operator reports the storage size of a type or object in bytes. Its result has type size_t, so %zu is the correct printf conversion specifier.
#include <stdio.h>
#include <stddef.h>
int main(void) {
int x = 42;
double y = 3.5;
printf("int: %zu bytes\n", sizeof x);
printf("double: %zu bytes\n", sizeof y);
printf("address of x: %p\n", (void *)&x);
printf("address of y: %p\n", (void *)&y);
unsigned char *bytes = (unsigned char *)&x;
printf("bytes of x:");
for (size_t i = 0; i < sizeof x; i++) {
printf(" %02x", bytes[i]);
}
printf("\n");
return 0;
}The exact sizes and addresses depend on the implementation, compiler, operating system, and execution. A common system has 4-byte int and 8-byte double, but C does not require those exact sizes.
C guarantees that sizeof(char) is 1. A byte in C means the size of a char, not necessarily eight bits. The number of bits in a byte is given by CHAR_BIT in <limits.h>.
| Type | Common size | What the bytes represent |
|---|---|---|
| `char` | 1 byte | A character or small integer |
| `int` | 4 bytes | A signed integer |
| `float` | 4 bytes | A floating-point value |
| `double` | 8 bytes | A more precise floating-point value |
Addresses and object representation
The address-of operator, &, produces the address where an object is stored. An address is commonly displayed in hexadecimal. Do not assume that two objects have particular addresses or that addresses remain the same between runs.
An object representation is the sequence of bytes used to store a value. Viewing an object through an unsigned char * is allowed. The output can reveal byte order. In little-endian storage, the least significant byte appears at the lowest address. In big-endian storage, the most significant byte appears first.
Exercise
Why should a program use %zu when printing the result of sizeof?
Show answer
sizeof produces a value of type size_t, and %zu is the conversion specifier defined for that unsigned size type.