Download as pdf or txt
Download as pdf or txt
You are on page 1of 46

Data structure and

programming II
Chapter 8- Pointer

Prepared by:
Dr. VALY Dona and Mr. NOU Sotheany, Mr. BOU Channa
1
Lecture overview
❑ Overall lectures

1. Introduction to algorithm 7. Recursive


2. Basic data types and statements 8. Pointers
3. Control structures and Loop 9. Linked Lists
4. Array 10. Stacks and Queues
5. Data structure 11. Sorting algorithms
6. Sub-programs 12. Trees

C++
2
Outline

▪ What is pointer?

▪ What are the advantages of using pointer?

▪ How to use pointer

▪ Examples

3
Introduction
❑ Computer Memory

▪ To understand pointers, you should have knowledge about address in


computer memory

▪ A computer memory location has an address and holds a content (value)

▪ The address is a numerical number (expressed in hexadecimal)

▪ An integer value consumes 4 bytes of memory

4
Introduction
❑ Computer Memory

▪ Each variable we create in the program has a location in the computer’s memory

▪ The value of the variable is stored in the assigned location

▪ To know where the data of normal variable is stored, we use operator &
▪ & gives the address occupied by a variable

▪ Example:
▪ If num is a variable, then &num gives the address of that variable

5
Introduction
❑ What is pointer?
▪ A pointer is a variable that holds the memory address of another variable of the
same type.
▪ Pointers are used to access the memory address and values at that address.

pointer* variable address

value

point to variable
name

An example of a pointer variable


pointing to a normal variable
6
Pointer Vs. Normal variable
❑ Remark
▪ A normal variable is used to store value, while a pointer variable is used to
store address (reference) of another variable
▪ Pointers are representation of addresses
▪ We can have a pointer to any variable type

7
Advantages of using pointer?
❑ Some main advantages
1. Use less memory
▪ Dynamic memory allocation
2. Program runs faster
▪ Increase execution speed and reduce execution time
3. Efficient when work with array, structure, list, stack, queue, …
4. Provide another way to access array element
5. Instead of copying data, pointer just point to an existing data
6. A function can return more than one value by passing via
function argument
8
Pointer Operator
❑ What?
▪ Two operators when work with pointer
▪ Address operator (reference operator)
▪ It uses &
▪ It returns memory address
▪ Indirection operator (deference operator or value operator)
▪ It uses *
▪ It returns value

9
Pointer Declaration
❑ Syntax

10
Pointer Initialization
❑ Syntax

11
Access to Pointer Variable
❑ Syntax

12
Example 1
❑ Not using pointer

What are the values of a and b here? a is 1, b is 2 13


Example 2:
❑ Using pointer

What are the values of a and b here? a is 2, b is 1 14


Pointer and Array

15
Pointer and Array
❑ Remark

▪ Suppose we have variables


▪ Var arr[10]: integer
▪ Var *p:integer

▪ Array name arr represents the address of the first elements of this array (&arr[0])

▪ We can say
▪ p = arr; // p point to the first element (arr[0]) in the array

▪ When a pointer points to an array, the value of the pointer is the first array element
▪ write(*p) 16
NOTE
❑ Reference (&) Vs. Deference (*) operator

▪ &: to get address of any variable

▪ *: to get value at the address that the point stores

Example:
▪ If an integer variable, say n, is stored in memory address 0xf1bd23,
and n contains a value of 5.

Then:
Reference operator &n gives the value of 0xf1bd23
Deference operator *n gives the value of 5
17
Q&A
18
Example 1: Using C++

▪ Suppose we have program as follows

#include<iostream>
using namespace std;
int main(){
int num=10;
int *ptr;
ptr = &num;
cout<<“num=”<<num<<endl;
cout<<“&num=”<<&num<<endl;
cout<<“ptr=”<<ptr<<endl;
cout<<“*ptr=”<<*ptr<<endl;
}
19
Example 2: Using C++

#include<iostream>
▪ Suppose we have program as follow
using namespace std; Output
int main(){
int *pc, c;
c=5;

cout<<“Address of c: ”<<&c<<endl;
cout<<“Value of c: ”<<c<<endl;
pc = &c;
cout<<“Address that pc holds: ”<<pc<<endl;
cout<<“Value of address that pc holds: ”<<*pc<<endl;
c = 11;
cout<<“Address that pc holds: ”<<pc<<endl;
cout<<“Value of address that pc holds: ”<<*pc<<endl;
*pc = 2;
cout<<“Address of c: ”<<&c<<endl;
cout<<“Value of c: ”<<c<<endl;
}

20
Size of Data Type

❑ Display size of variable using sizeof

C++ program
21
Q&A
22
Practice
❑ Exercises
1. Write a C++ program that declares and initializes any values to a variable of type float, integer
and string. The program then display the value and address (in hexadecimal form) for each
variable.

2. Write a C++ program to get two integer numbers from a user then swap the values of those two
variables and display them on screen.

3. Create a subprogram to swap the values of the four parameters. The first two parameters
exchange each other. The last two parameters exchange each other.

4. Create a function to solve quadratic equation. The function takes 6 parameters. The functions
solve roots then store in parameters. Prototype of this function is defined as below:
void solveEquation(float a, float b, float c, float *x1, float *x2, float *delta)

23
24
25
26
NOTE
27
Remarks
❑ Using pointer with single star (*) and double star (**)
#include<iostream> ▪ The variable i is an int, and set to the value 42.
using namespace std; ▪ pi is a pointer-to-int, and set to the address of i.
int main(){ ▪ ppi is a pointer-to-pointer-to-int, and set to the address of pi.
int i = 50;
int *pi = &i;
int **ppi = &pi;
cout<<*pi<<endl; **ppi *p i
cout<<**ppi<<endl;
}

https://www.youtube.com/watch?v=8ViFuvTezIc 28
https://www.quora.com/What-do-the-two-asterisks-signify-in-C++-when-passing-int-**array
Remarks
❑ Using pointer with single star in parameter of function
#include<iostream>
With this function declaration getA, there are two possibilities:
using namespace std;
1. This function can takes an array of integers as a parameter
void getA(int *pi ){ 2. This function can also take an integer, passed by reference, as a
//do something parameter
count<<*pi<<endl;
}
int main(){
int i = 42;
int *p=&i;
int arr1[]={1,2,7};
getA(arr1);
getA(&i);
getA(*p);
} 29
Understanding header file
❑ Definition

✓ A header file is a file that stores the list of functions or variables created by a user.

✓ With header file, it allows programmers to pack their codes as functions in a separated external file
which allow them to store functions in just a single file and reuse those functions when needed.

✓ Header file has .h or .hpp extension. We create a header file then put our functions there.

✓ Header file can be included to a normal .cpp source code file by using:

#include “headerFilename.h” or #include “headerFilename.hpp”

30
Creating a header file
❑ Example

Calling to function
created in header file

Write a C++ program to test


importing and using header file

Create a header file and name it as header.h 31


Q&A
32
Example 1
❑ Address operator on normal variable (not pointer)
▪ Suppose we have C++ program as follows

#include<iostream>
using namespace std;
int main(){
int num1=10;
int num2=20;
int num3=30;
cout<<&num1<<endl;
cout<<&num2<<endl;
cout<<&num3<<endl;
}
33
Example 1
❑ Address operator
▪ Suppose we have program as follow

#include<iostream>
#include<iostream> using namespace std;
using namespace std; int main(){
int main(){ int num=10;
int num=10; int *p;
cout<<“Value of number: ”<<num<<endl; p=&num;
cout<<“Address of number: ”<<&num<<endl; cout<<“Address that p stores: ”<<p<<endl;
} cout<<“Value at that address : ”<<*p<<endl;
}

34
Pointer variables
❑ Syntax
▪ We can assign and de-assign any space in memory using Pointer variables

▪ A pointer is a variable that stores the address of another variable

▪ Alternative syntax for declaring a pointer


▪ dataType *variableName;
▪ dataType* variableName;
▪ dataType * varaibleName;

▪ Example: Create a pointer variable


▪ int *num; string *s;
▪ int* num; float *f;
▪ Student * s; char *c;

35
Pointer variables
❑ More examples of creating pointer variables
▪ A pointer to an integer value
▪ int *p1;
▪ A pointer to a double value
▪ double *p2;
▪ Another valid syntax
▪ int* p1;
▪ int * p2;
▪ int *p3, *p4;
▪ Invalid syntax
▪ int p1*;

36
Example of Value Operator
❑ Value operator
▪ Suppose we have program as follows
#include<iostream>
using namespace std;
int main(){
int num=10;
int *ptr;

ptr = &num;
cout<<“num=”<<num<<endl;
cout<<“&num=”<<&num<<endl;
cout<<“ptr=”<<ptr<<endl;
cout<<“*ptr=”<<*ptr<<endl;
} 37
NOTE
❑ Reference (&) Vs. Deference (*) operator

▪ &: to get address of any variable

▪ *: to get value at the address that the point stores

▪ Example:
▪ If an integer variable, say n, is stored in memory address 0xf1bd23, and it contains a
value of 5
▪ Then
▪ Reference operator (&n) gives the value of 0xf1bd23
▪ Deference operator (*n) gives the value of 5

38
Example

#include<iostream>
▪ Suppose we have program as follow
using namespace std; Output
int main(){
int *pc, c;
c=5;

cout<<“Address of c: ”<<&c<<endl;
cout<<“Value of c: ”<<c<<endl;
pc = &c;
cout<<“Address that pc holds: ”<<pc<<endl;
cout<<“Value of address that pc holds: ”<<*pc<<endl;
c = 11;
cout<<“Address that pc holds: ”<<pc<<endl;
cout<<“Value of address that pc holds: ”<<*pc<<endl;
*pc = 2;
cout<<“Address of c: ”<<&c<<endl;
cout<<“Value of c: ”<<c<<endl;
}

39
Example: Display address using cout and printf

▪ Suppose we have program as follow

#include<iostream>
#include<stdio.h>
Output
using namespace std;
int main(){
int n=5;
int *p;
p=&n;
cout<<n<<" "<<&n<<endl;
cout<<p<<" "<<*p<<endl;
printf("\nn=%d, address of n=%p", n, &n);
printf("\np stores %d which is the address of
n,\n value of that address is: %d\n", p, *p);
}

40
Using pointer to swap two values via a function
parameter

void swapNum(int *a, int *b){


//codes to swap parameter values
}
int main(){
int n1=5, n2=10;
swapNum(&n1, &n2);
cout<<n1<<n2;
}

41
Homework
❑ Reading: Linked List

1. What is linked list? Single linked list? Double linked list?

2. Why linked list is important? Give some differences between array and linked list?

3. How to implement linked list in C++?


1. Give an example of a program implementing and using linked list with source code

*NOTE:

-Deadline: 11pm on 28st, Monday Jan 2019


-Submit .pdf file (max 2 pages) to google classroom (make sure to write your name and student ID)

42
Note
❑ Constant pointer Vs. Pointer to a constant
▪ Constant pointer
▪ Address stored in pointer is constant
▪ That address can not be changed (always points to the same address)
▪ The value stored at that address can be changed
▪ Pointer to a constant
▪ Pointer is pointing to a constant
▪ Address stored in pointer can be changed
▪ Pointer always point to a constant value

const int x=10;


int x=10, y=20; int y=20;
int *p=&x; //point to non-constant integer const int *p=&x; //
*p=20; //change value *p=20; //error, cuz value can not be changed
p=&py; //point to y instead p=&y; //ok, address can be changed
*p=100; //error, cuz p is pointing to a constant integer
43
Example 1
❑ Address operator
▪ Suppose we have program as follow

#include<iostream>
using namespace std;
int main(){
int num=10;
cout<<“Value of number: ”<<num<<endl;
cout<<“Address of number: ”<<&num<<endl;
}

44
C Programming
❑ Code syntax
▪ All C program statement begins inside a function called main()
▪ The main function is always called when the program first executes
▪ To access the standard functions that comes with compiler, a header with the
▪ #include <stdio.h> need to be included on top
▪ Structure of code
#include <stdio.h>
#include <stdio.h> int main(){
printf(“Hello World!”);
int main(){
printf(“Welcome to C Programming.”);
… Write your code here … }
}
Example of code in C programming

▪ Each line of code ends with a semicolon ;


45
Remarks
❑ Using pointer with single star (*) and double star (**)
#include<iostream>
With this function declaration getB, there are two possibilities:
using namespace std; 1. This function can takes a 2-dimensional array (matrix) of
void getB(int **pi){ integers as a parameter
//do something 2. This function can also take an array of integers, passed by
reference, as a parameter
}
int main(){
int i = 42;
int arr1[]={1,2,7};
int *p=arr1;
int arr2[][]={1,2,7;2,3,4};
getB(arr2);
getB(&arr1);
//getB(p);
} 46

You might also like