CodeBlanks Logo Icon CodeBlanks

Pointers

C# course · Expert · Lesson 8/47

Learn memory addresses with pointers like int*.

What is a pointer (int*)?

A pointer holds the memory address of a variable. In C#, int* p; declares p as a pointer to an integer. &x takes the address of x and *p (dereference) reads or writes the value at that address.

Pointers are valid only inside unsafe blocks and cannot directly reference managed types such as string or object. This boundary keeps GC object movement safe.

Dereference and pointer arithmetic

Accessing the value at the address held by a pointer is called dereference, written *p. *p = 20; writes 20 to that address; int v = *p; reads it.

Pointer arithmetic is also possible: p + 1 advances to the next int address (4 bytes forward). This is handy for fast loops over arrays and yields performance gains.

Exercise Print a value via a pointer

Mark Main as unsafe. Declare int a = 7;, take its address with int* p = &a; and print the value with Console.WriteLine(*p);.

Show example solution
unsafe static void Main() { int a = 7; int* p = &a; Console.WriteLine(*p); }
Example solution:
using System;

class Program
{
    unsafe static void Main()
    {
        int a = 7;
        int* p = &a;
        Console.WriteLine(*p);
    }
}

Test yourself

  1. Pointer declaration

    int x = 5;
    ____ p = &x;
    Show answer
    int x = 5;
    int* p = &x;
  2. What does *p do?

    • Takes the address of p
    • Reads/writes the value at the address p points to
    • Creates a new pointer
    • Deletes p
    Show answer

    Reads/writes the value at the address p points to — Correct. *p (dereference) accesses the value at the address.

  3. Match the pointer syntax

    &x
    Address of x
    *p
    Dereference
    int*
    Pointer to int type
    p + 1
    Next int address

All lessons in Expert