Pointers

Learn about the purpose of pointers in C, about declaring and dereferencing them, and about the implications of the size of a pointer.

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 basic idea is that 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.

There is a code example below that illustrates this more clearly.

Purpose of pointers

Pointers allow us to work with dynamically allocated memory blocks on the heap. We can also use pointers to deal with stack variables, but in most cases this just isn’t necessary.

As pointers can be used to manually, directly access a block of memory, they are used a lot for strings and structs. It’s not difficult to imagine that passing a large block of memory (such as a struct that contains many things) to a function would require copying all that data on the stack. Passing the address of such a block of memory 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. Passing the address of a variable to make it accessible in a function is called passing by reference. Passing the value of a variable by allocating a new local variable and copying its value into it is called passing by value.

A working example

To use a pointer, we need to know how to declare a pointer, how to store an address of a memory location in it, and how to use it to access that memory location.

Declaring a pointer

Here is how to declare a pointer and store an address in it:

Create a free account to access the full course.

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