Main

Lecture 4

Today we will continue working with C, focusing on dynamic memory allocation, and loops. Code from lecture (with some additions) can be cloned with

git clone https://brnorris03@bitbucket.org/brnorris03/cis330exercises.git

Note that this is no longer on ix or shell.uoregon -- future lecture code will continue to be added to the above Bitbucket repository, so you should be able to just git pull after you clone it the first time.

1. Allocating memory and freeing it

  • Anatomy of malloc
  • Separate declaration and allocation
  • When should we free memory

2. Multidimensional arrays

int numbers[2][4];   // A 2-D array of integers

3. Pointers

  1. int **numbers;
  2. const int numRows = 3, numColumns = 3;
  3. int i;
  4.  
  5. numbers = (int **) malloc ( numRows * sizeof(int *) );
  6. for (i = 0; i < numRows; i++) {
  7.   numbers[i] = (int *) malloc ( numColumns * sizeof(int) );
  8. }

When you use malloc, you simply "reserve" chunks of memory and keep track of their location. You still don't have any values stored in the memory, i.e., it is uninitialized.

To initialize all values to something reasonable, for example 0 in the case of an integer array, you can change the above code as follows.

  1. int **numbers;
  2. const int numRows = 3, numColumns = 3;
  3. int i;
  4.  
  5. numbers = (int **) malloc ( numRows * sizeof(int *) );
  6. for (i = 0; i < numRows; i++) {
  7.   numbers[i] = (int *) malloc ( numColumns * sizeof(int) );
  8.   memset(numbers[i], 0, numColumns * sizeof(int)); // set values to 0
  9. }

You can also do it without memset, but it can be less efficient:

  1. int **numbers;
  2. const int numRows = 3, numColumns = 3;
  3. int i, j;
  4.  
  5. numbers = (int **) malloc ( numRows * sizeof(int *) );
  6. for (i = 0; i < numRows; i++) {
  7.   numbers[i] = (int *) malloc ( numColumns * sizeof(int) );
  8.   for (j = 0; j < numColumns; j++) {
  9.     numbers[i][j] = 0;
  10.   }
  11. }

Now all the values in the 3x3 numbers array are initialized to 0:

4. Getting started with bash

  • Bourne shell (sh) is a shell, or command-line interpreter, for computer operating systems. It was developed by Stephen Bourne at Bell Labs and released in 1977.
  • Bash (the Bourne-Again shell) was later developed for the GNU project. Bash incorporates features from the Bourne shell, csh, and ksh.
  • Bash Introduction (also see schedule)
  • Important concepts:
    • Variables: environment and local
    • Input and output redirection
    • Pipes
    • Signals
    • Operators
    • Control flow (conditionals, loops)
  • Examples

Green Marinee theme adapted by David Gilbert, powered by PmWiki