The & address operator
- C course
- Beginner
- Lesson 72/116
- 5 min
Learn to take a variable's address with &.
The & address operator
The & operator gives the memory address of a variable. This address can be assigned to a pointer so that the pointer refers to that variable.
int x = 10;
int *ptr = &x;
printf("%p\n", (void*)ptr); /* prints the address */The address is the variable's location in memory; it may differ between runs. The %p format specifier is used to print addresses. Without an address, you cannot tell a pointer which variable to track.
The & operator with scanf
The scanf function asks for a variable's address to put input into it. That is why & is used.
int age;
printf("Age: ");
scanf("%d", &age); /* writes to age's address */
printf("%d\n", age);Without & before age, scanf does not work; the function would not know where to write. This is an everyday use of addresses.
Practice Take the addresses of two variables
Define int a = 3, b = 5;. Take each address with int *pa = &a, *pb = &b;. Print the values with printf("%d %d\n", a, b);. Output should be 3 5.
Starter code
#include <stdio.h>
int main(void) {
int a = 3, b = 5;
/* assign addresses of a and b to pa and pb */
/* print a and b with printf %d %d */
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
int a = 3, b = 5;
int *pa = &a, *pb = &b;
printf("%d %d\n", a, b);
return 0;
}Expected output
3 5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Take an address and assign to a pointer
int x = 5;
int *ptr = ____; /* ptr holds x's address */
int x = 5;
int *ptr = &x; /* ptr holds x's address */
Explanation: Answer is &x. The & operator takes the address.
2 What does & do in scanf("%d", &x)?
- Gives the address of x Correct answer
- Resets x
- Prints x
- Gives the value of x
Explanation: &x gives the address of x; scanf writes to that address.
3 Match address and pointer
| Term | Meaning |
|---|---|
& |
address operator |
int * |
int pointer type |
%p |
address format |
scanf |
writes to address |