1 What is the pointer

1.1 Arrays and pointers

1.2 Pointers and dynamic memory management

  • Otherwise, we have to manage memory ourselves using pointers. Bascially, memory in C can be auotmatic, static or dynamic.
    • Variables in automatic memory are managed by the computer on the stack, when it goes out of scope, the varible disappears.
    • Static variables essentially live forever.
    • Dynamic memory is allocated in the heap, and its lifetime is managed by users.
  • Mini-glossary:
    • scope: Where a variable is visible - basically C variables have block scope
      • variables either live within a pair of curly braces (inlucdes variables in parentheses just before block such as function arguments and the counter in a for loop),
      • or they are visible thorughout the file.
    • stack: Computer memory is divided into a stack (small) and a heap (big).
      • Automatic varianbles are put on the stack;
      • dynamcic variables are put in the heap.
      • Hence if you have a very large array, you would use dynamic memory allocation even if you knwe its size at initialization.
    • More details above stack and heap can be found in Memory management in C
  • Any variable in memory has an address represented as a 64-bit integer in most operating systems.
    • A pointer is basically an integer containing the address of a block of memory.
    • This is what is returned by functions such as malloc.
    • In C, a pointer is dentoed by *.
    • However, the * notation is confusing because its interpreation depends on whehter you are using it in a declaraiton or not.
    • In a declaration
  • To get the actual address value, we can use the & address opertor.
    • This is often used so that a function can alter the value of an argument passed in (e.g. see address.c below).

1.4 Pointers to pointers to pointers

  • Must remember that a pointer is simply a name for an integer that represents an address;
  • since it is an integer, it also has an address

1.5 More on pointers

  • Now func is a pointer to a funciton that takes a pair of ints and returns an int. Finally, add a typedef so that we can use func as a new type
  • which allows us to create arrays of function pointers, higher order functions etc as shown in the following example.

2 Examples

2.1 Pointer version of Pell’s equation

  • The previous version by using arry can be found in recursion

3 compile C programs by Make

4 References

  • Bronson, G. J., (2006). “A First Book of ANSI C”, 4nd, McGraw-Hill, Inc.
  • Kernighan, B. W. and Ritchie, D., (1988). “C Programming Language”, 2nd, Prentice Hall.
  • Cheng, H. H., (1996). “C for Engineers and Scientists :An interpretive approach”, Pearson.
  • Bryant, R. E. and O’Hallaron D, R., (2003). “Computer systems: a programmer’s perspective”, 3nd, Prentice Hall Upper Saddle River
  • Computational Statistics in Python