Arrays_Strings_Pointers in C++
Arrays_Strings_Pointers in C++
Using
Aderaw Semma
May-2025
Chapter V
Arrays, Strings and Pointers in C++
2
Objectives
Learn about arrays
4
I. Array Introduction
An array is a collection of a fixed number of components all of
the same data type. C++ provides a data structure, the array,
which stores a fixed-size sequential collection of elements of the
same type.
12
Accessing array elements
An element is accessed by indexing the array name. This is
done by placing the index of the element within square
brackets after the name of the array.
13
Cont…
Assume a 5-element int array – int x[5] = {8,5,3,9,6};
When you access x[2], the CPU calculates where that item is in
memory by taking the start address of x (i.e. 100) and adding
the product of the index, 2, times the size of the data type (i.e.
int = 4 bytes)
x[2] => int. @ address 100 + 2*4 = 108
x[3] => int. @ address 100 + 3*4 = 112
x[i] @ start address of array + i * (size of array type)
C++ does not stop you from attempting to access an element
beyond the end of the array – x[6] => int. @ address 100 +
6*4 = 124 (Garbage!!) 14
Cont…
Compiler must be able to figure out how much memory to
allocate at compiletime
type name[size1][size2]...[sizeN];
int threedim[5][10][4];
17
Two-Dimensional Arrays:
The simplest form of the multidimensional array is the two-
dimensional array. A two-dimensional array is, in essence, a list
of one-dimensional arrays.
type arrayName [ x ][ y ];
Where type can be any valid C++ data type and arrayName
will be a valid C++ identifier. A two dimensional array can be
think as a table, which will have x number of rows and y
number of columns. 18
Cont…
Two-dimensional array : collection of a fixed number of
components (of the same type) arranged in two dimensions–
Sometimes called matrices or tables
Declaration syntax:
intExp1and intExp2are expressions with positive integer values
specifying the number of rows and columns in the array
Two-dimensional arrays can be initialized when they are
declared: Elements of each row are enclosed within braces
and separated by commas All rows are enclosed within
braces For number arrays, unspecified elements are set to 0
Ways to process a two-dimensional array: Process entire
array Row processing : process a single row at a time
Column processing : process a single column at a time
Each row and each column of a two-dimensional array is a one-
dimensional array To process, use algorithms similar to one dimensional arrays 19
Cont…
Examples:
To initialize row number 4 (fifth row) to 0:
20
Cont..
Array Input Examples:
To input into row number 4 (fifth row):
21
Cont…
Example of Array Sum by Column: To find the sum of values of
each individual column:
22
Cont…
Some Restrictions on Array Processing
Aggregate operation : any operation that manipulates the
entire array as a single unit Not allowed on arrays in C++
Example:
Solution:
23
Cont…
Arrays as Parameters to Functions
Arrays are passed by reference only
Do not use symbol &when declaring an array as a formal
parameter
Size of the array is usually omitted If provided, it is ignored
by the compiler • Example:
Can prevent a function from changing the actual parameter
when passed by reference Use const in the declaration of
the formal parameter • Example:
25
Cont…
Thus far arrays can be thought of 1-dimensional (linear) sets
only indexed with 1 value (coordinate)
Matrix data
Images (2-D)
Index w/ 2 coordinates
(row,col)
26
Cont…
2D: Provide size along both dimensions (normally rows first
then columns)
Access w/ 2 indices
27
Cont…
A 2-dimensional array a, which contains three rows and four
columns can be shown as below:
The above statement will take 4th element from the 3rd row of
the array. You can verify it in the above diagram.
30
Cont…
#include <iostream>
using namespace std;
int main ()
{
// an array with 5 rows and 2 columns.
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
// output each array element's value
for ( int i = 0; i < 5; i++ )
for ( int j = 0; j < 2; j++ )
{
cout << "a[" << i << "][" << j << "]: ";
cout << a[i][j]<< endl;
}
31
Cont…
When the above code is compiled and executed, it produces
the following result:
As explained above, you can have arrays with any number of
dimensions, although it is likely that most of the arrays you
32
N-dimensional Array
collection of a fixed number of elements arranged in n
dimensions (n >= 1)
Declaration syntax:
33
Multi dimension Array
Declaration
2D: Provide size along both dimensions (normally rows first
then columns)
Access 2 indices
Declaration: int my_matrix[2][3];
Access elements with appropriate indices
My_matrix[0][1] evaluates to 3, and my_matrix[1][2]
evaluates to 2
3D: Access data 3 indices
Declaration: unsigned char image[2][4][3];
Up to human to interpret meaning of dimensions
Planes x Rows x Cols
35
Linearization of
Multidimensional Arrays
In a computer, multidimensional arrays must still be stored in
memory which is addressed linearly (1-Dimensional)
C/C++ use a policy that lower dimensions are placed next to
each other followed by each higher level dimension
36
Cont…
37
II. String Manipulation
There
using Arrays
are two types of strings commonly use in C++
programming language:
39
Cont…
A character array might not contain the null character, but the
last character in a C-string is always the null character.
As you will see, the null character should not appear anywhere
in the C-string except the last position. In addition, C-strings
are stored in (one dimensional) character arrays.
The following are examples of C-strings:
"John L. Johnson"
"Hello there."
From the definition of C-strings, it is clear that there is a
difference between 'A' and "A".
The first one is character A; the second is C-string A. Because
C-strings are null terminated, "A" represents two characters: 'A'
and '\0'. Similarly, the C-string "Hello" represents six
characters: 'H', 'e', 'l', 'l', 'o', and '\0'.
40
Cont…
To store 'A', we need only one memory cell of type char; to
store "A", we need two memory cells of type char—one for 'A'
and one for '\0'. Similarly, to store the C-string "Hello" in
computer memory, we need six memory cells of type char.
Consider the following example
char str[] = "C++";
In the above code, str is a string and it holds 4 character.
Although, "C++" has 3 character, the null character \0 is added
to the end of the string automatically.
Other ways of defining the string:
char str[4] = "C++";
char str[] = {'C','+','+','\0'};
char str[4] = {'C','+','+','\0'};
Like arrays, it is not necessary to use all the space allocated for the
string. For example: char str[100] = "C++"; 41
Cont…
The following declaration and initialization create a string
consisting of the word "Hello". To hold the null character at the
end of the array, the size of the character array containing the
string is one more than the number of characters in the word
"Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization, then you can write
the above statement as follows:
char greeting[] = "Hello";
Following is the memory presentation of above defined string
in C++:
42
Cont…
Actually, you do not place the null character at the end of a
string constant. The C++ compiler automatically places the '\0'
at the end of the string when it initializes the array. Let us try
to print above-mentioned string:
43
Cont…
C++ supports a wide range of functions that manipulate null-
terminated strings: C++ provides a set of functions that can be
used for C-string manipulation. The header file cstring
describes these functions.
44
Cont…
To use these functions, the program must include the header
file cstring via the include statement. That is, the following
statement must be included in the program:
#include
45
String Comparison
In C++, C-strings are compared character by character using
the system’s collating sequence. Let us assume that you use the
ASCII character set.
1. The C-string "Air" is less than the C-string "Boat" because the first
character of "Air" is less than the first character of "Boat".
2. The C-string "Air" is less than the C-string "An" because the first
characters of both strings are the same, but the second character 'i'
of "Air" is less than the second character 'n' of "An".
3. The C-string "Bill" is less than the C-string "Billy" because the first
four characters of "Bill" and "Billy" are the same, but the fifth
character of "Bill", which is '\0' (the null character), is less than the
fifth character of "Billy", which is 'y'. (Recall that C-strings in C++
are null terminated.)
4. The C-string "Hello" is less than "hello" because the first character
'H' of the C-string "Hello" is less than the first character 'h' of the C-
string "hello". 46
Cont…
Example: C++ program to display a string entered by user.
47
Cont…
Notice that, in second example only "programming" is
displayed instead of "Programming is fun". It is because The
extraction operator >> considers a space has a terminating
character. Consider the following example: which read and
display an entire line entered by user.
To read the text containing blank space, cin.get function can be used. This
function takes two arguments. First argument is the name of the string
(address of first element of string) and second argument is the maximum
48
size of the array.
Passing Array to a Function
in C++ Programming
Arrays can be passed to a function as an argument. Consider
this example to pass one-dimensional array to a function:
Example: C++ Program to display marks of 5 students by
passing one-dimensional array to a function.
49
Cont…
When an array is passed as an argument to a function, only the
name of an array is used as argument. The argument used
marks in the above code represents the memory address of first
element of array marks[5]. And the formal argument int m[5] in
function declaration decays to int* m;.
Multidimensional array
with dimension more
than 2 can be passed in
similar way as two
dimensional array.
51
III. POINTERS
In the later chapters, you learned that C++’s data types are
classified into three categories: simple, structured, and
pointers. Until now, only the first two data types are covered.
Now we will discusses the third data type called the pointer
data type. You will first learn how to declare pointer variables
(or pointers, for short) and manipulate the data to which they
point.
52
Basic Concept of Pointers
In earlier chapters, variables have been explained as locations
in the computer's memory which can be accessed by their
identifier (their name).
This way, the program does not need to care about the physical
address of the data in memory; it simply uses the identifier
whenever it needs to refer to the variable.
53
Cont…
These single-byte memory cells are ordered in a way that
allows data representations larger than one byte to occupy
memory cells that have consecutive addresses.
55
Pointer Variables and
Declaration
Pointers are the powerful feature of C++ programming, which
differs it from other popular programming languages like Java,
Visual Basic etc.
For example: In 1KB memory, there are 1024 bytes and each
byte is given an address (0 - 1023). As you know every
variable is a memory location and every memory location has
its address defined which can be accessed using ampersand
56
(&) operator which denotes an address in memory.
Cont…
Consider the following, which will print the address of the
variables defined:
type *var-name; 58
Cont…
Here, type is the pointer's base type; it must be a valid C++
type and var-name is the name of the pointer variable.
OR,
int* p;
59
Cont…
The statement above defines a pointer variable p. The pointer
p holds the memory address. The asterisk is a dereference
operator which means pointer to.
60
Cont…
Example: C++ Program to demonstrate the working of pointer.
61
Cont…
The output of the above program is
62
Explanation of Program:
When c = 5; the value 5 is stored in the address of variable c.
ptr++ 64
Cont…
The ptr will point to the location 1004 because each time ptr is
incremented, it will point to the next integer. This operation will
move the pointer to next memory location without impacting
actual value at the memory location.
66
Cont…
The out put of the above code is:
Pointers are the variables that hold address. Pointers can point
at cells of an array not only single variable. Consider this
example:
Int *ptr;
int a[5];
67
Cont…
Suppose, pointer needs to point to the fourth element of an
array, that is, hold address of fourth array element in above
case.
Since ptr points to the third element in the above example, ptr
+ 1 points to the fourth element. You may think that, ptr + 1
may hold the address of byte next to ptr.
69
Cont…
70
Cont…
Output
71
Cont…
Example: C++ Program to display address of array elements
using pointer notation.
72
Cont….
You know that, pointer ptr holds the address and expression
*ptr gives the content in that address. Similarly, *(ptr + 1)
gives the content in address ptr + 1. Consider this code below:
73
Cont…
Example: C++ Program to insert and display data entered by
using pointer notation.
74
Cont…
75
Revisiting function calling by
reference (using pointers)
In function chapter, you learned about passing arguments to a
function. This is pass by value because actual value is passed.
There is another way of passing argument in which actual
value is not passed; only the reference to that value is passed.
Consider this example .
76
Cont…
77
Cont…
In main(), two integer variables are defined. And those
integers are passed to a function swap() by reference.
78
Cont…
There is another way of doing this same exact task using
pointers. Consider this example:
79
Cont…
The output of this example is same as before. In this case, the
address of variable is passed during function call rather than
variable itself.
80
Cont…
The *n1 and *n2 gives the value stored at address n1 and n2
respectively.
81
82