Like HowStuffWorks on Facebook!

How C Programming Works

Some Pointers about Pointers in C

When your C program is loaded into memory (typically the random-access memory, or RAM, in your computer), each piece of the program is associated with an address in memory. This includes the variables you're using to hold certain data. Each time your program calls a function, it loads that function and all of its associated data into memory just long enough to run that function and return a value. If you pass parameters to the function, C automatically makes a copy of the value to use in the function.

Sometimes when you run a function, though, you want to make some permanent change to the data at its original memory location. If C makes a copy of data to use in the function, the original data remains unchanged. If you want to change that original data, you have to pass a pointer to its memory address (pass by reference) instead of passing its value to the function (pass by value).

Pointers are used everywhere in C, so if you want to use the C language fully you have to have a good understanding of pointers. A pointer is a variable like other variables, but its purpose is to store the memory address of some other data. The pointer also has a data type so it knows how to recognize the bits at that memory address.

When you look at two variables side-by-side in C code, you may not always recognize the pointer. This can be a challenge for even the most experienced C programmers. When you first create a pointer, though, it's more obvious because there must be an asterisk immediately before the variable name. This is known as the indirection operator in C. The following example code creates an integer i and a pointer to an integer p:

int i;

int *p;

Currently there is no value assigned to either i or p. Next, let's assign a value to i and then assign p to point to the address of i.

i = 3;

p = &i;

Here you can see the ampersand (&) used as the address operator immediately before i, meaning the "address of i." You don't have to know what that address is to make the assignment. That's good, because it will likely be different every time you run the program! Instead, the address operator will determine the address associated with that variable while the program is running. Without the address operator, the assignment p=i would assign p the memory address of 3, literally, rather than the memory address of the variable i.

Next, let's look at how you can use pointers in C code and the challenges you'll want to be prepared for.