Archive

Posts Tagged ‘pointers’

*Pointers

February 20th, 2009

In "The C Programming Language" by Kerinighan and Ritchie (K&R), pointers are defined as, "a variable that contains the address of another variable." By address, they mean memory address, a number used by the CPU to indicate a given portion of memory. In Java, a developer never has to deal with memory addresses it is all handled behind the scenes. In C, pointers can "create more compact and efficient code" and "are sometimes the only way to express a computation," according to K&R. Below are some visual examples to help with understanding pointers:

Pointing to a variable with a pointer

Pointing to a variable with a pointer

In the above image we are create a variable of type int and setting it to 5. Then, we are creating a pointer of type int and pointing it to our variable's memory address. The ampersand (&) is used to get the memory address, in our example 0xFE, of a variable. In the next image, you can see some of the power of using pointers:

Pointer math to access array elements

Pointer math to access array elements

In the above image, an integer array is being created with a size of 3. The numbers 0, 1, and 2 are being loaded into the array and then a pointer is then getting pointed to the array. At the bottom are examples of using pointer arithmetic to access array elements. Calling *ptr++ twice is the same thing as calling *ptr+=2.

Behind the scenes the address is merely being increased by the size of the data type. Let's say an int is 32 bits (4 bytes) long, then when you increment a pointer, you are merely adding 32 bits or 4 bytes to your memory address. Giving you the starting point of the next element in the array.

You can also set up an array of pointers or set pointers to functions as well. If you want to learn more about pointers I suggest: http://boredzo.org/pointers/

rjett Uncategorized ,