C Pointer? What is it for?

Book Sadprasid
3 min readJan 5, 2021

A pointer in C is a variable that stores an address of another variable — I’m sure this is pretty straightforward. The tricky part of C pointers lies in understanding their purpose and why you might need them.

In this post, I summarized contents from websites, youtube videos, class notes and textbooks that helped me crack this mystery. If you are going through the process of learning C, I hope this can help you a bit.

Before I ramble on about why programmers might have a need for pointers, here is a quick reminder of the basics:

Pointer?

In the C language, pointer is a variable that stores an address of another variable. It can be used with any data types by using the following format to declare:

int i = 0;

int *ptr = &i;

The operator ampersand(&) gives an address of the variable while the operator * is a de-referencer meaning it gives access to the value kept in the address the pointer points to. The above statement then assigns the address of i to a pointer variable ptr. Now, ptr is said to point to i.

What is the purpose of a C pointer? Why do you need access to a specific memory address?

Functions in C accept arguments by passing or copying values to the function stack. This sometimes is referred to as pass-by-value. Since functions in C do not actually have access to the variables that got passed to them, any changes that are made to the variables will not be saved outside of the scope of the function. This can be problematic because some functions need to make changes to the actual variables. This is where pointer becomes useful as it gives access to memory outside of the current stack frame. Though, it is important to note that a pointer can only assist with gaining access to variables in the frame below the current frame.

pointer.c

In the file pointer.c, there is a simple function that is meant to increment a number that gets passed in through the parameter by one. The function is written as followed:

However, when the code is run it shows that there has been no change made to the variable. This is due to the reason that only the value of the variable is copied to the increment function. Changes made to this variable are not visible to the rest of the program. In other words, the variable i inside of increment(), even though it has the same name, it is not the same variable as the int i outside of the function.

To overcome this challenge, instead of passing the increment function the actual variable, pass its pointer. This will give the current function access to the actual variable i which is out of the scope when this function gets executed. The function might look like this:

Need more resources? Check these out:

--

--