CSE 40872 Lecture 003

Topic:Data Structures (Arrays)
Author: Peter Bui <pbui@cse.nd.edu>
Date: August 31, 2009

Arrays Definition

Array
Set of consecutive memory locations used to store data of the same type
int     mInts[128];
char    mString[MAX_STRLEN];

const char *mStrings[NSTRINGS] = { "Aww", "Herro", "Prz" };

C string is just an array of chars.

Arrays Properties

Arrays best when you know how many elements are needed ahead of time.

Binning Example

Problem
Find the first non-repeating letter in a string.

Input:

In hoc signo vinces.
E pluribus unum.

Output:

h
E

Naive Solution

Naive Solution: O(N2)

# For each letter in String, check if letter appears
# more than once
for C in String:
    i = 0
    for CC in String:
        if C.lower() == CC.lower(): i += 1
        if i >= 1:  break
    if i == 1:
        return C

Binning Solution

Binning Solution: O(N)

char letter_count[NLETTERS];
char *sptr;

for(sptr = s; *sptr != 0; sptr++)
    if (isalpha(*sptr))
        letter_count[tolower(*sptr) - 'a']++;
for(sptr = s; *sptr != 0; sptr++)
    if (isalpha(*sptr))
        if (letter_count[tolower(*sptr) - 'a'] == 1)
            return *sptr;

Complete binning example.

Dynamic Allocation

Arrays best when you have a fixed and bounded size set.

Input:

5 4
0 1 2 3
0 1 2 3
0 1 2 3
0 1 2 3
0 1 2 3

Matrix Example

Allocate Matrix

int **mMatrix;

mMatrix = malloc(sizeof(int*) * mRows);
for (r = 0; r < mRows; r++)
    mMatrix[r] = malloc(sizeof(int) * mColumns);

// Remember to free!

Complete matrix example.