How C Programming Works

Using Pointers Correctly in C

If you want to become proficient in C programming, you'll need a firm grasp of how to effectively use pointers in your code.
If you want to become proficient in C programming, you'll need a firm grasp of how to effectively use pointers in your code.

Once you have a pointer, you can use that in place of a variable of the same data type in operations and function calls. In the following example, the pointer to i is used instead of i within a larger operation. The asterisk used with the p (*p) indicates that the operation should use the value that p is pointing to at that memory address, not the memory address itself:

int b;

b = *p + 2;

Without pointers, it's nearly impossible to divide tasks into functions outside of main in your C program. To illustrate this, consider you've created a variable in main called h that stores the user's height to the nearest centimeter. You also call a function you've written named setHeight that prompts the user to set that height value. The lines in your main function might look something like this:

int h;

setHeight(h); /* There is a potential problem here. */

This function call will try to pass the value of h to setHeight. However, when the function finishes running, the value of h will be unchanged because the function only used a copy of it and then discarded it when it finished running.

If you want to change h itself, you should first ensure that the function can take a pointer to an existing value rather than a new copy of a value. The first line of setHeight, then, would use a pointer instead of a value as its parameter (note the indirection operator):

setHeight(int *height) { /* Function statements go here */ }

Then, you have two choices for calling setHeight. The first is to use the address operator for h as the passed parameter (&h). The other is to create a separate pointer to h and pass that instead. The following shows both options:

setHeight(&h); /* Pass the address of h to the function */

int *p;

p = &h;

setHeight(p); /* Pass a separate pointer to the address of h to the function */

The second option reveals a common challenge when using pointers. The challenge is having multiple pointers to the same value. This means that any change in that one value affects all its pointers at once. This could be a good or bad thing, depending on what you're trying to accomplish in your program. Again, mastering the use of pointers is an important key to mastering C programming. Practice with pointers as much as possible so you'll be ready to face these challenges.

The C features we've explored so far are typical in other programming languages, too. Next, though, we'll look at C's demands for careful memory management.