You are on page 1of 44

Data Structure

Mr Zahi Al Chami
Chap 3: Pointers and Structures
Introduction
 The variable that stores the address of another variable
(like foo in the previous example) is what in C++ is called
a pointer.

1020 1024 1032

… … 100 … 1024 …
integer
pointer
Declare a pointer
 To declare a pointer, you should define its type and its
name as well.

 Example: int *p1, *p2, *p3 …

 Note that if we proceed as follows : int *p1,p2,p3 … only


p1 will be a pointer.
Address operator (&)
 The Address operator (&) provides us with the memory
address of a certain variable.

 For example:

1020 1024

… … 100 … … …
int a = 100;
cout << a; //prints 100
cout << &a; //prints 1024
The pointer variable
1020 1024 1032

… 88 100 … 1024 …
int a = 100;
int *p = &a; Result is:
cout << a << " " << &a <<endl; 100 1024
cout << p << " " << &p <<endl; 1024 1032

 The value of p is the address of the variable a.


 A pointer is a variable that has its own address.
Dereference operator (*)
 The pointers use the dereference operator (*) to access the
variable they point to directly.
1020 1024 1032

… 88 100 … 1024 …
int a = 100; Result is:
int *p = &a; 100
cout << a << endl; 1024
cout << &a << endl; 1024 100
cout << p << " " << *p << endl; 1032
cout << &p << endl;
Increment a pointer
 int x, y, *p
x=4
p=&x // p contains address of x
y=*p // y contains the content value of address p
(*p)++ // increment the content of address p by
1, which means increment x by 1

cout<<“value of x ”<<x; // x=5


cout<<“value of y “<<y; // y=4
Increment a pointer
 int x=5; int *p=&x;
cout<<x; -> 5;
cout<<p; -> address of x
cout<< &x; -> address of x
cout<< &p; -> address of p
cout<<*p; -> 5
x++;
cout<<x; -> 6
cout<<*p; ->6
(*p)++;
cout<< x; -> 7
cout<< (*p)++; -> ??
cout<<++*p; -> ??
cout<< *p++; -> ??
cout<< *++p; -> ??
Pass a pointer as parameter
The code

void doubleIt(int x, int * p)


{
*p = 2 * x;
}
int main(int argc, const char *
argv[])
{
int a = 16;
doubleIt(9, &a);
return 0;
}
Change the content of a pointer
Pointer to pointer
 Normally, a pointer contains the address of a variable.

 When we define a pointer to a pointer, the first pointer


contains the address of the second pointer, which points to
the location that contains the actual value as shown below.
Pointer to pointer example

What is the output?


Pointer to pointer example
NULL pointer
 NULL is a special value which indicates an empty pointer.

 If you try to access a NULL pointer, you will get an error.

A NULL pointer does not point to any variable.

int *p;
p = 0;
cout << p << endl; //prints 0
cout << &p << endl;//prints address of p
cout << *p << endl;//Error!
Static allocation vs dynamic allocation
 Static allocation is done when the program is initialized,
before its actual execution.

 Statically allocating a memory for a program means:


 Foresee the necessary memory space before running the
program.
 Reserve this space at compile time.
Static allocation vs dynamic allocation
 Dynamic allocation is done during program execution.

 This means that the dynamically allocated space is not


already in the program executable file when the operating
system loads the program into memory to run it.

 The request for space allocation to the operating system is


made during the execution of the program.
Dynamic allocation
 Allocation is done using the operator New.

 Deallocation of this memory is done with the operator


Delete.

 Even after leaving a function, the allocation persists if we


do not use the delete operator.
Operator New
 To dynamically allocate the memory, we proceed as
follows:
ptr = new SomeType;
Where ptr is a pointer of type SomeType.

 For example:
int* p = new int;
Uninitialized int variable

p
Operator New: Example
Operator Delete
 Free the allocated memory.

 It applies only to pointers with values obtained from the


new operator.

 Do not eliminate the pointer itself but the value pointed to


by this pointer.

Exemple:
Delete ad ;
Delete adc;
20
Operator Delete: Example

21
Pointers and Arrays
 The name of an array designates only the first element and
not the entire array.

22
Example

#include <iostream>
using namespace std;

void main (){


int a[5];
cout << "Address of a[0]: " << &a[0] << endl
<< "Name as pointer: " << a << endl;
}

Result:
Address of a[0]: 0x0065FDE4
Name as pointer: 0x0065FDE4

23
Dereferencing an array

This element is called


a[0] or *a

#include <iostream>
a[0] 2 using namespace std;
a void main(){
a[1] 4
int a[5] = {2,4,6,8,22};
a[2] 6 cout << *a << " "
<< a[0];
a[3] 8 } //main

a[4] 22

24
Dereferencing an array

#include <iostream>
a p using namespace std;
void main(){
a[0] 2 int a[5] = {2,4,6,8,22};
a[1] 4 int *p = a;
6 cout << a[0] << " "
a[2]
<< *p;
a[3] 8 }
a[4] 22
25 a

25
Dereferencing an array

a[0] or *(a + 0) 2 a
a[1] or *(a + 1) 4 a + 1
a[2] or *(a + 2) 6 a + 2
a[3] or *(a + 3) 8 a + 3
a[4] or *(a + 4) 22 a + 4

*(a+n) équivalent à a[n]


26
Double pointers 2D arrays
 So how does 2D arrays and pointers relate?

 A 2D array is viewed as an array of 1D arrays.

 That is, each row in a 2D array is a 1D array. Therefore given a 2D array


A: int A[m][n].

 We can think of A[0] as the address of row 0, A[1] as address of row 1


etc..

 Hence to find, say A[i][j] we do the following:


A[i][j]= *(A[i] + j) where A[i] = *(A+i)
= * ( *(A+i) + j)

27
Double pointers 2D arrays
 To dynamically create a 2D array, we write:
 int **B=new int *[n] // n is the number of rows
for(int i=0;i<n;i++)
B[i]=new int[m]; // each pointer points to an array and m is the
number of columns.

28
Exercises
 Write a procedure that takes as inputs two integers and swaps
their values using pointers.

 Write a program that calculate the sum of two numbers using


pointers.

 Write a function that returns the maximum element of an array


using the pointer formalism. The array and its size should be
passed as arguments.

 Write a function that finds the position of a value in an array.


The array, its size and the value are passed as arguments
29
Structure

30
Introduction
 What is a variable ?
 it is a cell of the memory having a type and a value.

 What to do if we need to store values having different


types in a same variable?
 Different values but same type => array
 Different types and values => Structure

31
Structure declaration

 The name of the structure is “record” and has 3 fields: two


variables of type int and one variable of type float.

 record item1, item2: it create two places in memory of


type record.

32
Accessing the fields of a structure
 The fields are handled like any other variable.

 We use the dot operator (.) to access the fields.

 Example:
 item1.number = 15 ;
 cout << item1.number ;
 cin >> item2.price ;
 item1.number++;

33
Structures including other structures

 employee.date_recruit.year, represents the year of


recruitment corresponding to the structure "employee"

34
Passing a structure by value

35
Passing a structure by reference

36
Passing a structure as a pointer

37
A function returning a structure

38
Array of structures
 Let us consider the following structure:

 Suppose we need to store the data of 100 people. So we


have to declare 100 variable of type personne.

 For this reason, it would be better to create an array of


structures
39
Example
 We have declared the following structure:

 In the main function:

40
Exercises
 Exercise 1:
using the below structure:
struct point{
double x;
double y;
};

First, input three points: A(2,5), B(6,1) and C(10,5) then:


1. Find AB, AC and BC.
2. Write a function that returns the coordinates of the midpoint of
two points.
3. Find the coordinates of the point M, midpoint of AB.

41
Exercises
 Exercise 2:
a structure student is defined as follows:

struct student{
char fname [20];
char lname [20];
int age;
char adresse [20];
double GPA;
};

1. Write a procedure that inputs the data of 5 students.


2. Write a function that returns the information of a student knowing his first name and last name.
3. Write a procedure that displays the information of a student having a GPA > 3.5
4. Write a function that returns the GPA average of the students.

42
Exercises
 Exercise 3:

a structure item is defined as follows:

struct item{
char name [20];
char description [20];
double price;
int quantity;
};

1. Write a procedure that inputs data of three items


2. Write a function that returns the item having the highest price
3. Write a procedure that sort the items in ascending order based on their prices.

43
Exercises
 Trace the algorithm below to find the result

 Trace the quicksort algorithm


44

You might also like