liveBook · Manning

Pointer

As explained in .NET in Action, Second Edition

A pointer is a value that represents a memory address and can be used to access or manipulate the addressed storage.

A pointer holds a memory address. Given a pointer to the right heap location, a function can access storage beyond its own stack frame. This matters when data must be allocated at runtime rather than sized when the function is compiled. section 10.3.4

Returning a dynamic array in C++

A function allocates an array with `ptr = new int[count]`, fills it through `ptr[i]`, and returns `ptr`. Unlike a fixed-size stack array, its size can come from a runtime argument. section 10.3.4

C# normally expresses the same read-and-return task with an `int[]`. Pointer access is also possible, but the array-copy example places it inside an `unsafe` block and uses `fixed` for both arrays. section 10.3.4

Listing 10.10 C# copy array using pointers instead of references
int[] CopyArray(int[] source)
{
  int length = source.Length;
  int[] target = new int[length];           #1
  unsafe                                    #2
  {
    fixed (int* pSource = source,           #3
           int* pTarget = target)
    {
      for (int i = 0; i < length; i++)
      {
        pTarget[i] = pSource[i];            #4
      }
    }
  }
  return target;                            #5
}

Follow `pSource[i]` and `pTarget[i]` through the copy loop to see where pointers replace ordinary array access. section 10.3.4

How .NET in Action, Second Edition covers it

How deep it goes
Explains pointer access through stack frames and heap allocation, then shows unsafe C# pointer use without detailing pointer representation.
Examples
Uses a C++ function returning a dynamic array and a C# function copying arrays with pointers.
What it assumes
Assumes familiarity with functions and arrays while defining the stack and heap before using pointers to contrast them.
What you can do after
Build it from scratch: copy a C# array using pointers within `unsafe` and `fixed` blocks.
How it connects
Links pointers to stack frames, heap allocation, dynamic arrays, unsafe code, and garbage collection.

Also explained in

Compare how 2 books explain pointer →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.