Skip to the task
Layout
Back to classic view
READTask 1 of 25 · step 1: Memory and sizeofMemory and sizeof
Memory and sizeof in practice/04/

Memory is numbered bytes. How many bytes char, int, double and a pointer take, and why the size of long differs between Windows and Linux.

Details & hint

So far a variable was "a box with a name". In this topic you see where that box actually is.

Memory is a row of bytes

Memory is a long row of bytes. A byte is 8 bits, and every byte has its own number, its address. A variable takes several bytes in a row, and its address is the number of its first byte.

100010041012… 53.14'A' int x – 4 bytesdouble d – 8 byteschar c – 1 &x = 1000, &d = 1004, &c = 1012

The addresses in the drawing are made up: real ones are long hexadecimal numbers, and different on every run.

How much room it takes: sizeof

sizeof tells how many bytes a type or a variable takes. Its value has the type size_t and is printed with %zu:

printf("int: %zu bytes\n", sizeof(int));
type bytes note
char 1 always
int 4 which is why the largest int is 2147483647 (topic 2)
double 8
int * (a pointer) 8 on a 64-bit computer
long 4 or 8 4 on Windows, 8 on Linux

The last row is the reason never to guess a size: write sizeof.

The address: &

&x is the address of the variable x. You can print it with %p:

printf("%p\n", (void *)&x);

In CLion on Windows you'll see something like 000000000061FE1C, on Linux 0x7ffd5e8a3c4c. The number may differ every time, so the program's logic doesn't depend on it. Addresses are easier to look at in the debugger: you'll do that in step 4.

An array in memory

An array's boxes lie one after another (topic 6). &t[1] is exactly sizeof(int) bytes after &t[0], so the address of t[i] is worked out at once: the start + i * sizeof(int). That's why the index starts at 0.

practice 04 CMakeLists.txt Code Diff
UNCHANGED This step does not change this file.
add_executable(p04_average main.c)
target_link_libraries(p04_average PRIVATE course_input)