Topics: FUNDAMENTALS
• Quick Revision
• Pointers and Arrays
OF STRUCTURED
• Dynamic Arrays
• Pointers to Structs
PROGRAMMING
Pointers – Part2
1
Quotes of the Day!
2
Contents
1. Pointers (Revisited)
2. Dynamic Memory (Revisited)
3. Pointers and Arrays
4. Dynamic Arrays
Creating and using, pointer arithmetic,
deleting.
5. Examples
1. Pointers (Revisited)
Initialization (1)
Address operator
1. Pointers (Revisited) – (cont.)
Initialization (2)
OR
1. Pointers (Revisited) – (cont.)
Initialization (2)
You cannot
dereference
a NULL
pointer.
1. Pointers (Revisited) – (cont.)
Pointers Arithmatic
• Only addition/subtraction on pointers
– No multiplication, division
• Can use ++ and -- on pointers
When adding one to a pointer, the pointer is made to point to the following
element of the same type, and, therefore, the size in bytes of the type it points
to is added to the pointer. 7
1. Pointers (Revisited) – (cont.)
Pointer Arithmetic
Undefined Behaviour!
You can display but you
cannot CHANGE values at
locations that are not yours!
the memory there is not
available to your program!
Could depend on compiler.
2. Dynamic Memory (Revisited)
Dynamic Variables Allocation
p1 = new int;
2. Dynamic Memory – (cont.)
Dynamic Variables De-allocation
• Avoid dangling pointers by assigning pointer
to NULL after delete.
// 0
You cannot dereference a null
pointer.
Practice ( Incrementing Pointers)
ptr++;
// use it then pointer moves to the next int position
++ptr;
// pointer moves to the next int position then use it
++*ptr;
// the value is incremented by 1 then used
*++ptr;
// pointer moves to the next int position then uses value
*ptr++;
// uses value then pointer moves to the next int position
11
int *ptr = new int (33); Practice (self study)
cout <<"Initial" << endl;
cout << ptr << '\t' << *ptr << endl;
cout << "++ptr;" << endl;
cout << ++ptr << '\t' << *ptr << endl;
cout << "ptr++;" << endl;
cout << ptr++ << '\t' << *ptr << endl;
cout << "ptr" << '\t' << ptr << endl;
cout << "++*ptr;" << endl;
cout << ++*ptr << endl;
cout << ptr << '\t' << *ptr << endl;
cout << "*++ptr;" << endl;
cout << *++ptr << endl;
cout << ptr << '\t' << *ptr << endl;
cout << "*ptr++;" << endl;
cout << *ptr++ << endl;
cout << ptr << '\t' << *ptr << endl; 12
PRACTICE
*++ptr; // pointer moves to the next int position then uses value
13
PRACTICE
*ptr++; // uses value then pointer moves to the next int position
14
Pointers
And Arrays
3. Pointers and Arrays
• Our previous Array variables
– Really pointer variables!
• Recall: arrays stored in memory
addresses, sequentially
– Array variable "refers to" first indexed variable
– So array variable is a kind of pointer variable!
• Example:
int arr[10];
int *p;
– arr and p are both pointer variables!
16
3. Pointers and Arrays – (cont.)
• So, can they be assigned to each other?
ILLEGAL !
Note that an array name is
exactly as a const int *
type.
Main difference is that pointers can be assigned new addresses, while arrays cannot.
arr can never be assigned anything, will always represent same block of 5 int elements.
17
3. Pointers and Arrays – (cont.)
18
3. Pointers and Arrays – (cont.)
19
3. Pointers and Arrays – (cont.)
Alternative Arrays Manipulation
20
3. Pointers and Arrays – (cont.)
Alternative Arrays Manipulation
• Using address arithmetic
This is equivalent to
ptr = &arr[1];
21
3. Pointers and Arrays – (cont.)
#include <iostream> Different ways to access array
using namespace std; elements using a pointer
void main ()
{
int numbers[5];
int * p;
p = numbers; *p = 10;
p++; *p = 20;
p = &numbers[2]; *p = 30;
p = numbers + 3; *p = 40;
p = numbers; *(p+4) = 50;
for (int n=0; n<5; n++)
cout << numbers[n] << ", ";
} 22
3. Pointers and Arrays – (cont.)
Alternative Arrays Manipulation
• To display all elements
23
3. Pointers and Arrays – (cont.)
Alternative Arrays Manipulation i=0 *(Ptr+0) 1st element
i=1 *(Ptr+1) 2nd element
• To display all elements i=2 *(Ptr+2) 3rd element
…. … …
24
3. Pointers and Arrays – (cont.)
Alternative Arrays Manipulation
• To display all elements Did ptr
move?
Ptr didn’t move
it still points to arr[0]
This is equivalent to
*ptr++ can be used too (moves ptr itself)
25
3. Pointers and Arrays – (cont.)
Alternative Arrays Manipulation
• To display all elements
26
3. Pointers and Arrays – (cont.)
Alternative Arrays Manipulation
• To display all elements
27
3. Pointers and Arrays – (cont.)
Brackets ([]) were explained as specifying the index of an
element of the array.
Well, these brackets are a dereferencing operator known
as offset operator.
They dereference the variable they follow just as * does,
but they also add the number between brackets to the
address being dereferenced.
28
3. POINTERS AND ARRAYS – (CONT.)
Summary:
You can use both dereference operators * and [] with
the array name or the pointer pointing to the array.
Except that you CANNOT change the address inside the
array name with ++.
Examples:
Int arr[5] = {0};
Int *ptr = arr;
for (int i=0; i<5; i++)
cout<<*(ptr + i); √ cout<<*(arr + i) √
cout<< ptr[i]; √ cout<< arr[i]; √
cout<< *ptr++; √ cout<<*arr++; X
29
REFERENCE VS. POINTER
On the surface, both references and pointers are very
similar as both are used to have one variable provide access
to another.
A pointer is a variable that holds a memory address and
has its own memory address. A reference is merely
another name for an already existing object. A reference
has the same memory address as the item it references.
A pointer can be re-assigned. Reference cannot and must
be assigned at initialization only.
30
REFERENCE VS. POINTER
A pointer needs to be dereferenced with * to access the
memory location it points to, whereas a reference can be
used directly.
A reference must refer to an object. Pointer can be
uninitialized, or can be assigned NULL directly, whereas
reference cannot. Since references can’t be NULL, they are
safer to use.
Pointers can iterate over an array or string, we can use ++ to
go to the next item that a pointer is pointing to.
➢ It’s better to use references as function parameters, and
pointers in creating dynamic data structures or accessing
arrays.
Reference: https://www.geeksforgeeks.org/pointers-vs-references-cpp/
31
Do It Yourself !
. What will be the output of the following code fragment ?
int *x, *y, z=7;
x = &z;
y = new int(6);
*x = 11;
++x;
cout << *x << “\t” << ++*y << ”\t” << z; garbage 7 11
++*ptr; // the value is
incremented by 1 then used
32
Dynamic
Arrays
4. Dynamic Arrays
Standard array
• Must specify size first - Fixed size
• May not know actual used size until program runs!
• Must "estimate" maximum size needed
– "Wastes" memory
Dynamic array
• Size not specified at program design time
• Determined while program runs
• Can grow and shrink as needed
34
4. Dynamic Arrays – (cont.)
Allocating Dynamic Array Variable
• Use new operator
– Dynamically allocates memory with pointer
variable at run time.
• Int *p = new int[10]
– Creates dynamically allocated array variable p,
with ten elements, base type int.
35
4. Dynamic Arrays – (cont.)
Allocating Dynamic Array Variable
• The advantage here is that we can assign a
variable as the array size. Something we
couldn’t do in automatic array variables.
36
4. Dynamic Arrays – (cont.)
Initializing Dynamic Array Variable
• Recall array variable zero initialization
37
4. Dynamic Arrays – (cont.)
Initializing Dynamic Array Variable
• Dynamic arrays zero initialization
Remember you can
also write
38
4. Dynamic Arrays – (cont.)
Processing Dynamic Array Variable
• Treated like any standard array.
dArr = new double[10];
dArr contains address of dArr[0]
dArr+1 evaluates to address of dArr[1]
dArr+2 evaluates to address of dArr[2]
… and so on.
39
4. Dynamic Arrays – (cont.)
De-allocating Dynamic Array Variable
• Returns memory to OS.
• Brackets indicates array; if you forget it,
only the first element will be deallocated!
• Remember dArr pointer still exists
dArr = NULL;
40
#include <iostream>
using namespace std;
void main()
{
int* a; // Pointer to int
int n; // Size needed for array
cin >> n; // Read in the size
a = new int[n]; // Allocate n ints, save ptr in a
for (int i=0; i<n; i++)
{
a[i] = i;
cout << a[i] << endl;
}
delete [] a; // Free memory pointed to by a
a = NULL; // Prevent using invalid memory reference
} 41
5. Examples – (cont.)
Example:
• Create an array of student
structures with variable size.
Compute the average of grades for
each student and the average of all
students.
42
Sample Run:
43
#include <iostream>
using namespace std;
#define GRADES 3
struct Std
{
int ID;
char name[20];
double grades[Grades];
double avg;
};
void fillArray(Std* studs,int size);
void ComputeAvgofAll(Std* studs,int size);
double ComputeAvgofOneStud(double grades[]);
void display(Std* studs,int size);
void main()
{
int numStd;
cout<< "How many students: ";
cin>> numStd; 44
// processing
// allocate
Std *students = new Std[numStd]; Static arrays are
passed by ref,
while dynamic
//fill data arrays are passed
fillArray (students, numStd); by pointer
//compute average of each students
for(int i=0; i<numStd; i++)
students[i].avg=computeAvgofOneStud (students[i].grades);
//compute average of all students
computeAvgofAll (students, numStd);
// output
display (students, numStd);
// dellocate
delete [] students;
students = nullptr;
}
45
void fillArray(Std* studs, int size)
{
for(int i=0;i<size;i++)
{
cout<<"ID: "; cin>> studs[i].ID;
cout<<"Name: "; cin>> studs[i].name;
for(int j=0; j<GRADES; j++)
{
cout<<"Subject#"<<j+1<<": ";
cin>> studs[i].grades[j];
}
}}
void display(Std* studs, int size)
{
cout<<"ID\t Name\t Average Score\n";
for(int i=0; i<size; i++)
cout<< studs[i].ID <<"\t"<< studs[i].name<<"\t“
<<studs[i].avg <<endl;
} 46
double ComputeAvgofOneStud(double grades[])
{
double Average=0.0;
for(int j=0;j< GRADES; j++)
Average += grades[j];
Average = Average/GRADES;
return Average;
}
void ComputeAvgofAll(Std* studs, int size)
{
double Average=0.0;
for(int i=0;i<size;i++)
Average += studs[i].avg;
Average = Average/size;
cout << "Average of All Students"<<Average<<endl;
}
47
Can we create a pointer to struct ??
Pointers to structures
Structures can be pointed to by its
own type of pointers.
The value of the pointer pmovie would
be assigned the address of
object amovie.
The arrow operator (->) is a dereference operator that is used
exclusively with pointers to objects that have members.
It accesses the member of an object directly from its address.
pmovie -> title
is equivalent to: (*pmovie).title
48
CAN WE CREATE A 2D DYNAMIC ARRAY ??
A 2D array is basically a 1D array of pointers, where
every pointer is pointing to a 1D array, which holds the
actual data. Number of rows and columns can be
obtained from user.
Google it !
(Not in Exam)
49
Online Quiz
Friday, 26/4/2024
at 9:00 pm
(Arrays – Structs - Fun by val – Fun by ref – 2D Arrays)
(Use any Gmail to sign in)
To do list:
• Sheet 8
• Home assignment 7
• Finish your project as soon as possible!
HOME ASSIGNMENT 7
Update the last assignment to match the following
requirement:
o Instead of using a fixed 1D array of structures,
use a dynamic array instead that will be created
according to the size the user specifies. And delete
the array at the end of the program.
Sample execution of the program is on our shared drive
51