Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

16.6. Creating and Using an Array of Pointers

Problem

You need to create, initialize, and use an array containing pointers.

Solution

The following code creates three pointers (TheNewBrush1, TheNewBrush2, and TheNewBrush3) that are inserted as elements in an array. The array of pointers to the NewBrush structure is created and set to a size of 3 so that it can hold each NewBrush structure. This newly defined array now contains undefined pointers. These undefined pointers should be initialized either to point to a value or to point to null. Here, all of the pointers in the array are initialized as null pointers. Finally, each NewBrush structure is then added to this array. Now we have a fully initialized array of pointers. From here we can use this array as we wish:

unsafe
{
    NewBrush theNewBrush1 = new NewBrush( );
    NewBrush theNewBrush2 = new NewBrush( );
    NewBrush theNewBrush3 = new NewBrush( );

    NewBrush*[] arrayOfNewBrushPtrs = new NewBrush*[3];
    for (int counter = 0; counter < 3; counter++)
    {
        arrayOfNewBrushPtrs[counter] = null;
    }

    arrayOfNewBrushPtrs[0] = &theNewBrush1;
    arrayOfNewBrushPtrs[1] = &theNewBrush2;
    arrayOfNewBrushPtrs[2] = &theNewBrush3;
}

Notice that the for loop initializes each pointer in the array to null before the array is used. This is usually a good practice so that you do not inadvertently use an uninitialized pointer. Using a pointer that points to null results in a NullReferenceException being thrown on current versions of the CLR. This device makes it easier ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata