Friday, August 31, 2007

Pointers

Pointers - Definition

  • Pointers provide an indirect method of accessing variables. The reason why pointers are hard to understand is because they aren't taught in a manner that is understandable. Think for a minute about a typical textbook. It will usually have a table of contents, some chapters, and an index. What if you were looking in the 'C' book for information on printf? You'd look at the index for printf. The index will tell you where information on printf is located within the book. Conceptually, this is how pointers work! Re-read this analogy if you didn't get it the first time. This is important. You must understand that pointers are indirect references.
  • You may be wondering, what is the point of this ? Why don't I just make all variables without the use of pointers? It's because sometimes you can't. What if you needed an array of ints, but didn't know the size of the array before hand? What if you needed a string, but it grew dynamically as the program ran? What if you need variables that are persistent through function use without declaring them global ? They are all solved through the use of pointers. Pointers are also essential in creating larger custom data structures, such as linked lists.
  • So now that you understand how pointers work, let's define them a little better.
    • A pointer when declared is just a reference. DECLARING A POINTER DOES NOT CREATE ANY SPACE FOR THE POINTER TO POINT TO. The main purpose of pointers is to allocate memory dynamically (Dynamic Memory Allocation).
    • A pointer is a reference to an area of memory in the heap. The heap is a dynamically allocated area of memory when the program runs.

void Pointers

  • void pointers can be assigned to any pointer value. It sometimes necessary to store/copy/move pointers without regard to the type it references.
  • You cannot dereference a void pointer.
  • Functions such as malloc, free, and scanf utilize void pointers.

No comments: