Pointers and Basic Structures in C++


Introduction and Summary

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.

Take a Study Break

SparkLife

Star Trek gets SEXY

Chris Pine and Zoe Saldana heat up the red carpet!

SparkLife

Are you afraid of relationships?

Auntie SparkNotes can help!

SparkLife

Wanna get JLaw's gorgeous glow?

Click here for simple, sexy makeup tricks!

SparkLife

Sexy starlet style

See every single look from the Met Gala!

SparkLife

Who'd be on your zombie-apocalypse crew?

We already dib'sed Genghis Khan.

Geek out!

The MindHut

Geeky Actors: Then and Now

Travel back in time!

The MindHut

10 Movies Better Than Their Books

What do you think?

The MindHut

How To Look Like J-Law...

When you don't look like J-Law.

The MindHut

12 Scientific Inaccuracies in Into Darkness

What did Star Trek get wrong?

The MindHut

Villains We Want These Actresses to Play

From super cute to super bad!