Menu
Coddy logo textTech

The Address-Of Operator (&)

Part of the Logic & Flow section of Coddy's C journey — lesson 3 of 63.

Now that you can declare pointers, you need to learn how to actually store a memory address in them. The address-of operator (&) is the key to getting the memory address of any variable.

When you place the & operator in front of a variable name, it returns the memory address where that variable is stored. Think of it as asking "Where does this variable live in memory?"

int age = 25;
int *ptr;
ptr = &age;    // Store the address of 'age' in 'ptr'

In this example, &age gives us the memory address of the age variable. We then assign this address to our pointer ptr. Now ptr "points to" the age variable.

The address-of operator is essential because it's the bridge between regular variables and pointers. Without it, you couldn't tell a pointer which variable to point to. Remember that the data types must match - you can only assign the address of an integer to a pointer declared for integers.

challenge icon

Challenge

Easy

Write a C program that demonstrates using the address-of operator to connect variables with pointers. Your program should:

  1. Declare an integer variable named number and initialize it with the value 42
  2. Declare a character variable named letter and initialize it with the value 'X'
  3. Declare a pointer to an integer named num_ptr
  4. Declare a pointer to a character named char_ptr
  5. Use the address-of operator to assign the address of number to num_ptr
  6. Use the address-of operator to assign the address of letter to char_ptr
  7. Print the addresses stored in both pointers using printf with the %p format specifier

Your output should display the pointer addresses in the following format:

Address of number: [address]
Address of letter: [address]

The actual memory addresses will vary between program runs, but the format and labels must match exactly as shown above.

Cheat sheet

The address-of operator (&) returns the memory address of a variable:

int age = 25;
int *ptr;
ptr = &age;    // Store the address of 'age' in 'ptr'

The address-of operator is essential for connecting variables with pointers. Data types must match - you can only assign the address of an integer to a pointer declared for integers.

Use %p format specifier to print pointer addresses with printf.

Try it yourself

#include <stdio.h>

int main() {
    // TODO: Write your code here
    // 1. Declare and initialize the variables
    // 2. Declare the pointers
    // 3. Use the address-of operator to assign addresses
    // 4. Print the addresses using the format shown
    
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow