Addresses and pointers
Read · 1 of 4
Where a variable lives
Every variable sits somewhere in memory, at an address. &x means "the address of x".
int *p = &x; makes p a pointer to an int holding x's address. *p means "the int that p points at": reading *p reads x, and *p = 9; changes x.
Two uses of *, two meanings: in a declaration it says "p is a pointer"; in an expression it follows the pointer.
Read this lesson as text
Every variable lives at an address. A pointer is a variable that holds one.
Where a variable lives
Every variable sits somewhere in memory, at an address. &x means "the address of x".
int *p = &x; makes p a pointer to an int holding x's address. *p means "the int that p points at": reading *p reads x, and *p = 9; changes x.
Two uses of *, two meanings: in a declaration it says "p is a pointer"; in an expression it follows the pointer.
Changing x through p
#include <stdio.h>
int main() {
int x = 4;
int *p = &x;
*p = *p * 10;
printf("%d %d\n", x, *p);
return 0;
}- Line 4: x holds 4, at some address in memory.
- Line 5: p holds x's address: p points at x.
- Line 6: *p reads x (4), times 10 is 40, and *p = stores it back into x.
- Line 7: x and *p are the same box, so both print 40.
Which one moved?
#include <stdio.h>
int main() {
int a = 1, b = 2;
int *p = &a;
*p = 5;
p = &b;
*p = *p + 10;
printf("%d %d\n", a, b);
return 0;
}What does this print?
- 5 12
- 15 2
- 1 12
Show the answer
5 12 First p points at a and sets it to 5. Then p is pointed at b, and b becomes 2 + 10.
Exercise: Double through a pointer
Read a number into n. Without writing n again after the scanf line, double it using the pointer p and print it with p.