← The C Language Lesson 23 of 77 · 10 XP

Addresses in memory

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

Every variable lies somewhere in memory, and that place has an address — the number of its first byte. You get it with the & operator:

int x = 42;
printf("%p\n", (void *)&x);    // for example 0x7ffd5e8c — it changes from run to run

You can picture memory as a long tape of numbered bytes. An int takes 4 bytes in a row, and &x is the address of the first of them.

The items of an array lie right next to each other, so their addresses differ by exactly the size of an item:

int a[3];
// &a[0] = 1000, &a[1] = 1004, &a[2] = 1008 (if an int is 4 bytes)

In expressions, an array's name turns into the address of its first item: a == &a[0].

Now it's clear why scanf needs &: the function is given the address where it will write the number it reads.

Task. Declare an array int a[5]. Print two numbers separated by a space: by how many items &a[3] and &a[0] differ, and by how many bytes. For bytes, cast the addresses to char *: (char *)&a[3] - (char *)&a[0].

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.