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,doubleandint *, with%zu; int x = 5; int *p = &x;– it printsxand*p(the same value), then*p = 7;andxagain;p == &x– pointers are compared by address;int *q = t;– a pointer to the start of an array:*q,*(q + 2)andq[3];int *r = NULL;and the checkr == 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):
- Click in the gutter next to the line
*p = 7;– a red dot (a breakpoint). - Debug (the green bug or Shift+F9).
- In the Variables window:
x = 5andp = {int *} 0x...– a pointer's value is an address. Expandp: inside is*p = 5. - F8 (Step Over):
xbecomes 7, although the line doesn't mentionx.
Expand t and q too: q's address is the same as the address where t starts.
Commit: Print addresses and pointers.