Pointers

In the previous section, we learned about the Heap memory structure. Pointers are our way of accessing and manipulating the Heap. This lesson will show you how!

Pointers represent one of the more powerful features of the C language, but also one of the most feared. Some of this fear and apprehension stems from the ridiculously obtuse ways that pointers may be used in C. Often tutorials and courses on C approach teaching pointers by asking the student to decipher bizarre looking pointer syntax combinations that truthfully are rarely used in practice. You may have seen bizarre looking pointer syntax, (and you may see it again), but typically, pointers do not have to be used in a horribly complicated way. Typically pointers are pretty straightforward.

The bottom line is, pointers allow you to work with dynamically allocated memory blocks. You will use pointers to deal with variables that have been allocated on the heap. (You can use pointers to deal with stack variables, but in most cases this just isn’t necessary).

The basic idea is, a pointer is a special data type in C, that contains an address to a location in memory. Think of a pointer as an arrow that points to the location of a block of memory that in turn contains actual data of interest. It’s not unlike the concept of a phone number, or a house address.

The purpose of pointers is to allow you to manually, directly access a block of memory. Pointers are used a lot for strings and structs. It’s not difficult to imagine that passing the address of a large block of memory (such as a struct that contains many things) to a function, is more efficient than making a copy of it and passing in that copy, only to delete that copy when your function is done with it. This is known as passing by reference versus passing by value. There is a code example below that illustrates this more clearly.

Declaring a pointer

Here is how to declare a pointer:

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy