Thomas Pearson C Programming/Pointer Basics

From Wikiversity
Jump to navigation Jump to search

Lesson objectives:[edit | edit source]

  • To understand what a pointer is on a fundamental level.
  • To understand how to use pointers to pass-by-reference, or pass around a variable's address.

Lesson[edit | edit source]

What is a pointer?:[edit | edit source]

A pointer is a variable holding a specific memory location. Most often, this memory location is that of a variable or array - but it can also be the location of a function (discussed seperately). This fact is very useful, as it allows us to remember where some data is, and then access it in a way that would not otherwise be feasible in any flexible manner. The main way this happens is when we need a function to alter some variable, but we don't know which variable in the function code itself, as it changes. Here, we do a pass-by-reference.

Passing by-reference:[edit | edit source]

As mentioned in functions, whenever we pass a variable to a function, the value is copied to the stack, and the function is then able to use this value. This is called a pass-by-value. Keep in mind that a pass-by-reference is actually just a pass-by-value for the memory address of the variable. Anyways, due to the value being copied, any changes made to the variable within the function are not permanent - they end with the function return. By using a pointer, however, we can tell the function to alter the memory address where the uncopied value is - allowing persistent change. Note that when the function returns, the copied value of the memory address has no persistent changes - so say you altered the pointer by decrementing it, this change wouldn't be permanent outside the function.

Dereferencing/indirection:[edit | edit source]

Dereferencing, or less commonly indirection, is the process of taking a memory address and accessing the value stored there. This is done using the (yet unmentioned) unary operator*. The opposite operator, for getting the memory address of a variable is the unary operator&. Type casting note: due to C's "weak typing", you can dereference a value you arbitrarily assign to a pointer - or even dereference a non-pointer type! You can also assign a non-pointer type the value of a pointer or address. This is a Bad Idea. Unless you are writing specific code which cannot accidentally be used in the wrong way, it's better to stick with an OS defined way of accessing certain information instead of hard-coding in addresses for these things.

Note: pointers and arrays:[edit | edit source]

Arrays are contiguously allocated chunks of memory. Pointers are allowed to have math performed on them. This means is it possible to iterate over arrays by using a pointer to the address (of the start of) the array. This is the main idea behind the advanced pointers topic.