Skip over navigation

Contents

Pointers and Basic Structures in C++

Introduction and Summary

Table of Contents

Terms

Pointers are variables that store the value of a location in memory. In essence they "point" to the location of any variable, in which case they are said to point to the variable in question. By using pointers, a function has the capability to change the value of a variable that resides outside the function's scope. Giving a pointer as an argument to a function is called "passing by reference," whereas variables are normally passed by value. This guide will discuss pointers as they relate to C++; for a review of pointers in general see the SparkNote on the topic.

Structs are used to collect a number of related variables into one structure, thereby creating a new kind of data type. Structs are less commonly used in C++ than in C because C++ implements classes, which can do all that structs do and more. Variables in a struct are accessed with the dot operator ".", and variables in a struct pointer are accessed with the membership access operator "->".

One way to use pointers with structs is to create linked lists, which are structures that can hold any number of "links." To create a new variable from an arbitrary pointer, use the new operator to allocate a piece of memory to point to. To free the memory again, use the delete operator with the pointer variable's name.

Arrays are a more basic structure that have a set number of elements. They can be initialized at declaration time by using the brace notation and listing the elements separated by commas. Multidimensional array require nested brace notation if they are to be initialized at the time of declaration. Elements are accessed through their respective indices inside of brackets. See the arrays SparkNote for a full treatment of this topic.

Follow Us