BETA Try the new lesson view
Code

Memory in a program

The first program: see what sizeof says, and your first pointer.

Create practice/08:

add_executable(p08_memory memory.c)

No course_input here: the program asks nothing.

memory.c:

  • four sizeofs: char, int, double and int *, with %zu;
  • int x = 5; int *p = &x; – it prints x and *p (the same value), then *p = 7; and x again;
  • p == &x – pointers are compared by address;
  • int *q = t; – a pointer to the start of an array: *q, *(q + 2) and q[3];
  • int *r = NULL; and the check r == NULL.

Run it

p08_memory and ▶:

char:   1 byte
int:    4 bytes
double: 8 bytes
int *:  8 bytes
x = 5, *p = 5
After *p = 7: x = 7
p points to x
*q = 10, *(q + 2) = 30, q[3] = 40
r points nowhere

x was never assigned 7, yet it changed: *p = 7 wrote to the same place.

Addresses in the debugger

The program doesn't print addresses: they differ every time. Look at them in the debugger (topic 4):

  1. Click in the gutter next to the line *p = 7; – a red dot (a breakpoint).
  2. Debug (the green bug or Shift+F9).
  3. In the Variables window: x = 5 and p = {int *} 0x... – a pointer's value is an address. Expand p: inside is *p = 5.
  4. F8 (Step Over): x becomes 7, although the line doesn't mention x.

Expand t and q too: q's address is the same as the address where t starts.

Commit: Print addresses and pointers.