0% found this document useful (0 votes)
53 views

Chapter Six: Introduction To Arrays, String and Pointers

This document provides an introduction to arrays, strings, and pointers in C++. It defines an array as a series of elements of the same type placed consecutively in memory that can be referenced using an index. Arrays allow storing multiple values of the same type without declaring separate variables. Strings are arrays of characters that are null-terminated. Pointers store the address of another variable in memory and can be used to indirectly access and manipulate variables. Key pointer operators are the address operator (&) and dereference operator (*).

Uploaded by

lalisa
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views

Chapter Six: Introduction To Arrays, String and Pointers

This document provides an introduction to arrays, strings, and pointers in C++. It defines an array as a series of elements of the same type placed consecutively in memory that can be referenced using an index. Arrays allow storing multiple values of the same type without declaring separate variables. Strings are arrays of characters that are null-terminated. Pointers store the address of another variable in memory and can be used to indirectly access and manipulate variables. Key pointer operators are the address operator (&) and dereference operator (*).

Uploaded by

lalisa
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 44

Chapter Six

Introduction to Arrays, String


and Pointers
What is an array?
Array is a series of elements of the same type placed

consecutively in memory that can be individually


referenced by adding an index to a unique name.
An array is a collection of data storage locations, each of

which holds the same type of data.


 Each storage location is called an element of the array.

An array is a collection of similar elements.


Cont…
Example: You may need to store five course marks.
0 1 2 3 4

index

elements

(int/float)
That means, we can store 5 values of type int/float,
without having to declare 5 different variables each with a
different identifier.
Cont…
An array contains multiple objects of identical types

stored sequentially in memory.


The individual objects in an array, referred to as array

elements, can be addressed using a number, the so-called


index or subscript.
The subscript is the number of elements in the array,

surrounded by square brackets.


Arrays in C++ are zero-bounded; that is the index of the
Properties of arrays

first element in the array is 0 and the last element is N-1,


where N is the size of the array.
It is illegal to refer to an element outside of the array

bounds, and your program will crash or have unexpected


results, depending on the compiler.
Array can only hold values of one type
Defining an array
Like any other variable, an array must be declared before it is

used and must be defined just like any other object.


In the array declaration one must define:

 The type of the array (i.e. integer, floating point, char


etc.)
 Name of the array,

 The total number of memory locations to be allocated or


the maximum value of each subscript. i.e. the number of
elements in the array.
Cont…
The general syntax for the declaration is:

data type arrayname[array size]


where data type is a valid object type (int, float...),
arrayname is a valid variable identifier and the array size,
that is enclosed within brackets [ ], specifies how many of
these elements the array contains.
Cont…
For instance, you can declare marks with six different

courses as following:

float mark[6];
Note: array size cannot be a variable whose value is set

while the program is running, since arrays are blocks of


static memory of a given size and the compiler must be
able to determine exactly how much memory it must
assign to the array before any instruction is considered.
Index for Array Elements
The subscript operator [] is used to access individual array

elements.
In C++ an index always begins at zero.

Example: marks[6];
Thus, the elements belonging to marks array are

[0], [1], [2], [3], [4], [5]


The index of the last array element is thus 1 lower than

the number of array elements.


Initializing an array
Arrays can be initialized when you define them.

 A list containing the values for the individual array

elements is used to initialize the array:

Example: int num[3] = { 30, 50, 80 };


A value of 30 is assigned to num[0], 50 to num[1], and 80

to num[2].
Cont…
If you initialize an array when you define it, you do not need to

state its length. Example: int num[] = { 30, 50, 80 };


In this case, the length of the array is equal to the number of

initial values.
If the array length is explicitly stated in the definition and is

larger than the number of initial values, any remaining array


elements are set to zero.
 If, in contrast, the number of initial values exceeds the array

length, the surplus values are ignored.


Cont…
The following array initialization way is the same with the
previous one:
int num[0] = 30,;
int num[1] = 50;
int num[2] = 80;
Accessing array elements
We can access an array elements just as it was a normal
variable. The format is the following:
name[index]
Example:
marks
To store the value 75 in the third element of marks a
suitable sentence would be:
marks[2] = 75;
Cont…
Again, to pass the value of the third element of marks to

the variable a, we could write:


a = marks[2];
Therefore, for all purposes, the expression marks[2] is

like any other variable of type int.


Cont…
At this point brackets [ ] perform two different tasks:

1. To set the size of arrays when declaring them

int marks[2] ; //declaration of an array


2. To specify indices for a concrete array element when
referring to it.
marks[2] = 75; //access to an element of the
array
Reading Assignment:

 Operations on Arrays
 finding the maximum member of an array
 finding the minimum member of an array
 searching values from the array
Multidimensional Arrays
Multidimensional arrays can be described as arrays of

arrays.
Each dimension is represented as a subscript in the array.

Therefore, a two-dimensional array has two subscripts; a

three-dimensional array has three subscripts; and so on.


Cont…

Matrix represents a bi-dimensional array of 3 per 5 values

of type int .
The way to declare this array would be: int matrix[3][5];
Cont…
For example, the way to reference the second element
vertically and fourth horizontally in an expression would be:
matrix[1][3]

Multidimensional arrays are not limited to two indices (two


dimensions). They can contain so many indices as needed,
although it is rare to have to represent more than 3 dimensions.
Initializing multidimensional array
You can initialize multidimensional arrays.

You can also assign the list of values to array elements in

order.
For instance, int marks[2][3]={2,4,7,8,32, 51};

The first three elements go into marks[0]; the next three

into marks[1]; and so forth.


Cont…
You initialize this array by writing
int marks[2][3]={2,4,7,8,32, 51};
OR
int marks[2][3] = { {2,4, 7},
{8,32,51}};
Cont…
The compiler ignores the inner braces, which make it

easier to understand how the numbers are distributed.


Each value must be separated by a comma, without regard

to the braces.
The entire initialization set must be within braces, and it

must end with a semicolon.


Strings of Characters.
A string is a sequence of character.

We have used null terminated <char> arrays to store and

manipulate strings.
A string is a consecutive sequence (i.e., array) of

characters which are terminated by a null character.


Initialization of Strings
Because strings of characters are ordinary arrays they
fulfill same rules as any array.
For example, if we want to initialize a string of characters
with predetermined values we can do it in a similar way to
any other array:
char mystring[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
Cont…
In this case we would have declared a string of characters

(array) of 6 elements of type char initialized with the


characters that compose Hello plus a null character '\0' .
Nevertheless, string of characters have an additional way

to initialize its values: using constant strings


Example:

char mystring [] = { 'H', 'e', 'l', 'l', 'o', '\0' };

char mystring [] = "Hello";


Cont…
Note: null character ( '\0' ) specifies the end of the string
in the first example and that, in the second case, when
using double quotes ( " ) it is automatically appended.
The assignation of multiple constants like double-quoted
constants ( " ) to arrays are only valid when initializing the
array, that is, at the moment when declared. So we can
"assign" a multiple constant to an Array only at the
moment of initializing it.
Example:
mystring="Hello"; mystring[] = "Hello";
neither would be: mystring = { 'H', 'e', 'l', 'l', 'o', '\0' };
Assigning Values to Strings
Just like any other variables, array of character can store
values using assignment operators.
mystring[0] = 'H';
mystring[1] = 'e';
mystring[2] = 'l';
mystring[3] = 'l';
mystring[4] = 'o';
mystring[5] = '\0';
But not allowed as mystring=“Hello”;
Reading Assignment
Functions to manipulate strings
 String length
 String Concatenation
 String Copy:
 String Compare
The End
Pointer
Variables are stored in concrete places of the computer

memory, each one with a unique address.


A pointer is a variable which stores the address of another

variable.
The only difference between pointer variable and regular

variable is the data they hold.


A pointer is a data type that points to another value stored

in memory.
Cont…
There are two pointer operators in C++:
 & the address operator
 * the dereference operator
The & operator always produces the memory address of
whatever it precedes.
The * operator, when used with pointers, either declares a
pointer or dereferences the pointer’s value.
The dereference operator can be literally translated to
"value pointed by" .
Cont…
Generally, objects can be accessed in two ways:
1. directly by their symbolic name, or
2. indirectly through a pointer.
The act of getting to an object via a pointer to it, is called
dereferencing the pointer. Pointer variables are defined to
point to objects of a specific type so that when the pointer is
dereferenced, a typed object is obtained.
Cont…
Note: We generally do not decide where the variable is to
be placed - fortunately that is something automatically
done by the compiler and the operating system on
runtime.
But once the operating system has assigned an address
there are some cases in which we may be interested in
knowing where the variable is stored.
This can be done by preceding the variable identifier by
an ampersand sign (&), which literally means,
"address of”. For example: ptr= &var;
Cont…
Suppose that var has been placed in the memory address
1776 and that we write the following:
var=25; The result will be the one shown in the following
diagram:
x=var;
ptr = &var;
Declaring pointers
Is reserving a memory location for a pointer variable in the
heap. Syntax:
type * pointer_name ;
To declare a pointer variable called int * p_age, do the
following:
int * p_age;
Whenever the dereference operator, *, appears in a variable
declaration, the variable being declared is always a pointer
variable.
Type is the data type pointed to by the pointer. This type is not
the type of the pointer itself, but the type of the data the pointer
points to.
Cont …
Note that the asterisk (*) used when declaring a pointer
only means that it is a pointer, and should not be
confused with the dereference operator, which is also
written with an asterisk (*). They are simply two different
things represented with the same sign.
Pointer variable Initialization
Pointers can have any name that is legal for other variables.
p_age is an integer pointer. The type of a pointer is very
important.
p_age can point only to integer values, never to floating-point
or other types.
To assign p_age the address of a variable, do the following:
int age = 26;
int * p_age; int age = 26;
p_age = &age; OR int * p_age = & age;
Cont…
Both ways are possible.
If you wanted to print the value of age, do the following:
cout<<age; //prints the value of age
Or by using pointers you can do it as follows
cout<<*p_age; //dereferences p_age;
Note: The dereference operator produces a value that tells
the pointer where to point. Without the *, (i.e
cout<<p_age), a cout statement would print an address
(the address of age). With the *, the cout prints the value
at that address.
Pointer operation
The Address of Operator &:
The & is a unary operator that returns the memory address
of its operand. For example, if var is an integer variable,
then &var is its address. This operator has the same
precedence and right-to-left associativity as the other
unary operators.
You should read the & operator as "the address of"
which means &var will be read as "the address of var".
Cont…
Indirection Operator *, it is the complement of &. It is a
unary operator that returns the value of the variable located
at the address specified by its operand.
Pointers and Arrays

An array name is just a pointer, nothing more. The array


name always points to the first element stored in the array.
There for , we can have the following valid C++ code:
int aray[5] = {10,20,30,40,50};
cout<< *(aray + 2); //prints aray[2];
Cont…
*(aray+2) takes the address stored in aray, adds 2 to the
address, and dereferences that location.
Consider the following character array:
char name[] = “C++ Programming”;
Cont…
What output do the following cout statements produce?
cout<<name[0]; // ____C__
cout<<*name; // _____C__
cout<<*(name+3); //_________
cout<<*(name+0); //____C____
References:
 Hid_cplus plus-tutorial pdf
 A complete Guide to programming in c++
 Visual c++ in 21 days Second Edition
 C++ Lecture All in One Addis Abeba univ.

You might also like