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

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 = &num;
    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

  1. Why cast to (void*) when printing addresses?
  2. Is &10 valid? Why or why not?
Show answers
  1. %p expects a void* for portability.
  2. 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).