C - Address-of operator
The address-of operator (&
) in C is used to get the memory address of a variable. This is a key concept for understanding pointers and memory management in C.
Learning Objectives
- Use
&
to obtain addresses safely and portably. - Print addresses with
%p
correctly.
Prerequisites
- C - Variables
- C - Pointers (overview)
What is the Address-of Operator?
The address-of operator (&
) returns the address in memory where a variable is stored. It is most often used with pointers.
Syntax
&variable_name
Simple Example
#include <stdio.h>
int main(void) {
int x = 10;
printf("Value of x: %d\n", x);
printf("Address of x: %p\n", (void*)&x);
return 0;
}
Using & with Pointers
You can assign the address of a variable to a pointer using &
:
#include <stdio.h>
int main(void) {
int num = 5;
int *ptr = #
printf("num = %d, *ptr = %d\n", num, *ptr);
printf("Address stored in ptr: %p\n", (void*)ptr);
return 0;
}
Passing by Reference
Passing the address of a variable to a function allows the function to modify the original variable:
#include <stdio.h>
void increment(int *p) {
(*p)++;
}
int main(void) {
int value = 7;
increment(&value);
printf("value after increment: %d\n", value);
return 0;
}
Checks for Understanding
- Why cast to
(void*)
when printing addresses? - Is
&10
valid? Why or why not?
Show answers
%p
expects avoid*
for portability.- No. You can’t take the address of a temporary/constant.
Common Pitfalls
- Cannot take the address of a constant or expression (e.g.,
&10
is invalid). - Do not return the address of a local variable from a function (it becomes invalid after the function ends).
- Always use the correct pointer type (e.g.,
int *p = &x;
for an int).