Data structures

Arrays - logical view

Arrays: a simplified memory view

Array syntax

Using arrays

Loops and arrays

Initializing arrays

Printing arrays

Array access

(Just more terminology you may run across)

What can go in arrays?

Common errors with arrays


Arrays as parameters

There are two aspects to consider with functions and arrays:
(i) passing an individual array element as a parameter to a function
(ii) passing the entire array as a parameter to a function

Passing array elements

Passing one element of an array to a function is just like passing a variable of the same type, we simply have to use the arrayName[position] syntax when passing the element.

Pass-by-reference (the default when passing whole arrays)

Making arrays pass-by-value

If we don't want a function to be able to change the contents of an array, we explicitly add the word const to the parameter list in the function definition, e.g.
void cannotChange(const float arr[], int val)
{
    // this function cannon alter the contents of the array parameter
}

Passing arrays and size

Example: fill array

void fillarray(int array[], int size);

int main()
{
   int myarray1[20], myarray2[12];

   printf("Filling first array\n");
   fillarray(myarray1, 20);

   printf("Filling second array\n");
   fillarray(myarray2, 12);
}

void fillarray(int array[], int size)
{
   int numRead; // variable to track how many things scanf read
   int value;           // variable for converted value
   bool valid;       // recording validity of input

   for (int index = 0; index < size; index++) {
       // get and test input value
       valid = false;
       do {
          printf("Enter a positive integer\n");
          int numRead = scanf("%d", &value);
          if (numRead <= 0) {
             printf("sorry, invalid input\n");
          }
       } while (numRead <= 0);

       // assign to array once valid entry obtained
       array[index] = value;
   }
}


Strings as arrays of characters

End-of-string character

"String" input: char arrays

String output: character arrays

fgets to read lines of text

The fgets function can be used to read an entire line of text into a character array, while also providing an upper limit on the number of characters to read.

The programmer may either specify the data is read from the keyboard (using the keyword stdin) or specify an open file pointer to use instead. (File pointers are discussed in the file io notes.)

A sample call would look like:
fgets(arrayName, maxSize, stdin);

cstring library functions

The library <cstring> includes useful functions for manipulating null-terminated character arrays.

(Note: this is NOT the same as the C++ string library and class.)

The library <cstdlib> also includes a few:

cstring library examples

#include <cstdio>
#include <cstring>

const int SIZE = 81;
typedef char mystring[SIZE];

int main()
{
   mystring surname1, given1, whole1;  // names for person 1
   mystring surname2, given2, whole2;  // names for person 2

   printf( "Person 1: enter your given name\n");
   fgets(given1, SIZE-1, stdin);
   printf( "and now your surname (family name)\n");
   fgets(surname1, SIZE-1, stdin);

   printf( "Person 2: enter your given name\n");
   fgets(given2, SIZE-1, stdin);
   printf( "and now your surname (family name)\n");
   fgets(surname2, SIZE-1, stdin);

   // create whole names for each by copying given name
   // then appending the surname
   strcpy(whole1, given1);
   strcat(whole1, " ");
   strcat(whole1, surname1);

   strcpy(whole2, given2);
   strcat(whole2, " ");
   strcat(whole2, surname2);

   // print them in order of last name
   if (strcmp(surname1, surname2) < 0) {
      printf("%s\n%s\n", whole1, whole2);
   } else if (strcmp(surname1, surname2) > 0) {
      printf("%s\n%s\n", whole2, whole1);
   } else {
       printf("You have the same names!\n");
   }
}

Checking and converting input

Example: frequency count

// assume gettext prompts a user to enter a paragraph
// with up to 1000 characters, and returns its size
//
// printcounts takes an array of 26 integers and
// prints out its contents

int main()
{
   char paragraph[1000];
   int alphacount[26];
   int textlength;

   textlength = gettext(paragraph, 1000);
   freqcount(paragraph, textlength, alphacount);
   printcounts(alphacount);
}

// freqcount records how often each letter of the alphabet
// appears in a character array. It stores the count for
// a,A in freq[0], the count for b,B in freq[1], etc

void freqcount(char text[], int size, int freq[])
{
   char nextchar;
   int asciival;

   // for each character in the block of text
   for (int index = 0; index < size; index++) {
       // get the next char and find its ascii value
       nextchar = text[index];
       asciival = int(nextchar);

       // 'A' to 'Z' have ascii values 65 to 90  
       if ((asciival >= 65) && (asciival <= 90)) {
          freq[asciival - 65] += 1;
       }
       // 'a' to 'z' have ascii values 97 to 122
       if ((asciival >= 97) && (asciival <= 122)) {
          freq[asciival - 97] += 1;
       }
   }
}

Example: matching brackets

// brack_check takes an array of text which includes
// left and right curly brackets and checks to see
// if the brackets match up correctly
//
// we do this by scanning through the text and counting
// how many brackets are currently "open", incrementing
// the count by 1 each time we see { and decrementing
// the count by 1 each time we see }
//
// the text is invalid if either:
//   we encounter a } when the current count is 0
// or at the end of the text the current count is not 0
//
// brack_check returns true for valid layouts,
// false for invalid

bool brack_check(char text[], int size)
{
    int opencount = 0;

    for (int index = 0; index < size; index++) {

        if (text[index] == '{') opencount++;

        if (text[index] == '}') {
             if (opencount == 0) return(false);
             else opencount--;
        }
    }

    if (opencount != 0) return(false);
    else return(true);
}

Multidimensional arrays


Arrays and dimensions

Two dimensional arrays

Passing multi-dim arrays as parameters

Example: tutorial marks

const int MAXSTUDENTS = 32;
const int MAXTUTES = 13;
typedef float Table[MAXSTUDENTS][MAXTUTES];

void readmarks(table grades, int students, int tutes);

int main()
{
   int numstudents, numtutes;
   Table grades98;

   // find out how many students and tutes
   printf("Enter the number of students and tutes\n");
   
   scanf("%d", &numstudents);
   scanf("%d", &numtries);

   // get the marks read in
   readmarks(grades98, numstudents, numtutes);
}

void readmarks(table grades, int students, int tutes)
{
   // go through each student
   for (int s = 0; s < students; s++) {

       // get all of that students marks
       for (int t = 0; t < tutes; t++) {

           // prompt the tutor and read the mark
           printf("Enter mark for student %d", s+1);
           printf(" tutorial %d\n", t+1);
           scanf("%f", &(grades[s][t]));

       }
   }
}

3D arrays: asteroids example

// representing a space as blocks of 1 cubic mile each,
// looking at a section 30 miles long, 10 high, and 50 wide
//
// Each array entry holds true if there is an asteroid
// in that cubic mile, false otherwise

const int Length = 30;
const int Height = 10;
const int Width = 50;

typedef bool Space[Length][Height][Width];

int main()
{
   Space region1;

   // initialise to no asteroids present
   for (int len = 0; len < Length; len++) {
       for (int hi = 0; hi < Height; hi++) {
           for (int wid = 0; wid < Width; wid++) {
               region1[len][hi][wid] = false;
           }
       }
   }

   // set asteroids in co-ordinates 
   // (0, 0, 0) and (12, 7, 43)
   region1[0][0][0] = true;
   region1[12][7][43] = true;
}