Arrays and Pointers
1 CUIT114/111 SEST, CUT 3/1/2017
Outline
Shortfalls of previous variables
The Array data type
One-dimensional arrays
Multidimensional Arrays (Matrices / Tables)
Examples
Pointers
Strings
2 CUIT114/111 SEST, CUT 3/1/2017
Shortfalls of previously studied variables
Variables store a single value
Requirement of many variables when dealing with
many instances
Reduced reusability
Too many lines of program code
3 CUIT114/111 SEST, CUT 3/1/2017
1. Arrays
Used to store a list of items,
Items have the same data type
Can define 100 name variables
As one array variable allowing storage of 100 names
Each item can be accessed
By array index
4 CUIT114/111 SEST, CUT 3/1/2017
Structure of an array
0 1 2
Array = stretch of several spaces adjacent to
one another.
Each space is recognised by an index (i.e.
Location)
First space = index 0
Last space in the above = index 9
Total spaces = 10
Amount of memory reserved
Dependent on data type of each item stored
Array variable
5 CUIT114/111 SEST, CUT 3/1/2017
Entire stretch given one name
Different types of arrays
1 row and 6 columns 1 dimensional array 1 x 5 array
2 rows and 3 columns 2 dimensional array 2 x 3 array
3 rows and 6 columns 2 dimensional array 3 x 6 array
6 CUIT114/111 SEST, CUT 3/1/2017
Defining array variables
datatype varname [size];
Size is the maximum number of items you wish to store in the
array
Define a 1x5 array called ids to hold decimal numbers
float ids[ 5] ;
Define a 4 x 3 array called wgt to hold character initials
#define ROW 4
#define COL 3
char wgt[ROW][COL];
Define an array moves that stores 7 values. Each value
is a 3x3 array. Each value in the 3x3 array is an integer
int moves[7][3][3];
7 CUIT114/111 SEST, CUT 3/1/2017
Knowing your array
Given
float ids[5];
This means ids[0] is an integer, ids[1] is an
integer, and so on.
Given
char wgt[4][3];
This means that wgt[0][0] is a character, wgt[0][1]
is a character, wgt[0][2] is a character, wgt[1][0],
wgt[1][1] and wgt[1][2] are characters and so on.
However wgt[0][3] is not valid since counting must
end at 3-1 = 2 for the columns (counting starts at
0)
8 CUIT114/111 SEST, CUT 3/1/2017
Initialising arrays with values
Create an array called char mnemonics [5] = {‘D’,
mnemonics from the ‘F’, ‘T’, ‘Z’, ‘W’ }
following table:
int distance [3][4] = {
‘D’ ‘F’ ‘T’ ‘Z’ ‘W’ {8, 3, 6, 4} ,
distance from the {5, 5, 7, 6} ,
{7, 9, 2, 7} };
following table: First row initialises
distance[0]
8 3 6 4 OR
5 5 7 6
int distance [3][4] = {8, 3,
7 9 2 7
6, 4, 5, 5, 7, 6, 7, 9, 2, 7}
y that stores three
integers and only int y [3] = {7}
initialises the first value All other values are initialised
to 7 and the rest to 0 to 0 by deafult.
9 CUIT114/111 SEST, CUT 3/1/2017
Knowing your values
int idx[5]; Indexing starts from 0.
Give the values of the
98 54 25 20 82
following:
7 6 3 9 7
idx[4]
idx[1][2]
wth[2][3]
float
4.65 wth[3][3];
3.44 3.62
Minions[2][5]
Minions[1][3]
3.57 2.34 4.36
2.356 8.56 9.34 Write C statements to
Add wth[2][1] and wth[1][2]
and store the result in wth[2]
[2].
Display value in wth[2][2].
Get user input into minions[1]
char minions[2][6]; [3]
10 CUIT114/111 SEST, CUT 3/1/2017
Example: indexing and manipulating a one-
dimensional array
A program to add all the
scores of 6 participants in a
table tennis team. Run Results
#include <stdio.h> Enter score (out of 10) for participant 1:
#define SIZE 6 3
int scores [SIZE];
void enter_scores() Enter score (out of 10) for participant 2:
{ for(int i=0; i<SIZE; i++) 7
{ Enter score (out of 10) for participant 3:
printf("Enter score (out of 10) for participant %d:\t",i+1); 2
scanf("%d",&scores[i]);
}
Enter score (out of 10) for participant 4:
} 5
int total_scores() Enter score (out of 10) for participant 5:
{ int total=0; 8
for(int i=0; i<SIZE; i++)
{ total += scores[i];
Enter score (out of 10) for participant 6:
} 8
return total;
}
int main()
{ Total Team Score: 33
enter_scores(); Process returned 0 (0x0) execution
printf("\n \n Total Team Score:\t %d", total_scores()); time : 13.653 s
return 0;
} Press any key to continue.
11 CUIT114/111 SEST, CUT 3/1/2017
Multidimensional arrays
Used to store data that can be represented as a matrix
Have rows and columns just like matrices
0 6 8
6 0 4
8 4 0
1 1 7
The above array has 4 rows and 3 columns
Suppose the array is called distance, then
7 is the distance between indexed city 3 and indexed city 2
indexed as distance[3][2]
Hence distance[3][2] = 7
3 is the row index, 2 is the column index
Indexing starts from 0 (zero)
12 CUIT114/111 SEST, CUT 3/1/2017
Defining a matrix variable
Declaring a matrix of characters called
screen having 25 rows and 80 columns
char screen[25][80];
Referring to 5th character in the 2nd row,
screen[1][4]
Top corner of the screen
screen[0][0]
Last bottom corner of screen
screen[24][79]
13 CUIT114/111 SEST, CUT 3/1/2017
Indexing and manipulation of a matrix
variable
Write a program that adds two matrices with
the following values
1 4 5
8 2 10
Can write/ initialise values in the matrices, row
by row
int matrix_a[2][1] = { {1}, {2} };
{1} are the contents of row 1
{2} are the contents of row 2
What matrix do you get when you write
14
int matrix_b[2][2] = {CUIT114/111
{1,0}, SEST,
{8,9} };
CUT 3/1/2017
Full Program
#include <stdio.h>
int m_1[2][1] = {{1},{8}}; //first matrix Make the
int m_2[2][1] = {{4},{2}}; //second matrix program
int f[2][1]; //final result matrix generic so
that size of
int main() matrix and
{ values in
int r=0, c=0; //r=row index, c=column index matrix are
for (r=0; r<2; r++) input by the
{ user
for(c=0; c<1; c++)
{
f[r][c] = m_1[r][c] + m_2[r][c];
printf("\n \nf[%d][%d] = %d \n", r, c, f[r][c]);
}
}
return 0;
}
15 CUIT114/111 SEST, CUT 3/1/2017
Exercise 1
Write a program that allows that processes
the contents of two matrices as follows:
Each matrix is 4x4.
The program must have
a function enter() for entering values of the two
matrices.
A function subtract() for subtracting the two matrices.
A function product() that finds the product of the two
matrices and then returns the resultant matrix.
The values in the matrices can be either float or
int.
16 CUIT114/111 SEST, CUT 3/1/2017
2. String
An array of characters
End of valid data marked with null or ‘\0’
Example
“My name is ?dont know”
“&%^56”
char name[10];
Uses the %s field specifier
17 CUIT114/111 SEST, CUT 3/1/2017
Input into a string variable
Given int scope; we write scanf(“%d”, &scope);
Given char name[15];
name is already an address.
No need for &
&name means an address of an address which is wrong
Can write:
printf(“Enter your first name”);
scanf(“%s”, name);
Printf(“Your name is %s”, name);
int val = strlen(name);
//to get the length(i.e. number of characters in the string
Find out the string functions that you can use in C
and their meanings.
18 CUIT114/111 SEST, CUT 3/1/2017
Initialising strings
Given
char name[10];
Statement Comment
name = “Ruvimbo” WRONG since name is pointer
and “Ruvimbo” is a string
constant
char *n = “Ruvimbo”; Defines a pointer to a string and
n = “Tinago” value can be changed
#include <string.h> Copies string to the one pointed
strcpy(name, “Ruvimbo”); to by name
char name[10] = “Ruvimbo”; Initialises a 10-character array
Char name [ ] = “Ruvimbo” Leaves size of array to compiler
Char name[10] = {‘R’, ‘u’, ‘v’,
‘i’, ‘m’, ‘b’, ‘o’}
19 CUIT114/111 SEST, CUT 3/1/2017
Manipulating Strings
These are manipulated the way you
manipulate arrays
Go through each item in the string using a loop of
your choice.
You can also string functions to manipulate
strings.
20 CUIT114/111 SEST, CUT 3/1/2017
Summary
Arrays allow you to store data of the same
type.
Arrays are versatile and allow you to handle a
lot of data.
Strings are special arrays for storing
sequences of characters.
Strings have special functions for
manipulating them and getting quick results.
Arrays and strings are widely used in any
system programming.
21 CUIT114/111 SEST, CUT 3/1/2017