Beruflich Dokumente
Kultur Dokumente
(Lecture 7)
By:
Dr. Norazah Yusof
FSKSM, UTM
Introduction
A pointer is a derived data type.
A data type built from one of the standard data type.
Pointer variables contain memory address of a variable.
Indirectly references a value.
and, an address.
The variable name is used by the programmer to
refer the memory location. The variables address
is the actual location in memory and only used by
the computer
The first variable uses name a, contains value 100 and located
at memory address 123456.
variable
name
content
123455
a
100
123456
123456
123460
123464
123465
address
4
Pointer Variables
Nom
&Nom
Pointer variables
Huruf
&Huruf
Nom
&Nom
??
x
??
y
10
Pointer variables
Example 3:
char Huruf;
int Nom;
char * x;
int * y;
Huruf = A;
Huruf
&Huruf A
&Huruf
x
Nom
&Nom 85
&Nom
y
Nom = 85;
x = &Huruf;
y = &Nom;
11
int *p;
int *p = &x;
p = &x;
12
Example 5:
// This program stores the address of a variable in a pointer.
#include <iostream>
using namespace std;
int main()
{
int x = 25, y=100;
int *ptr1;
// declaring pointer variable ptr1
int *ptr2 = &y;
// declare and initialize pointer variable ptr2
// ptr2 is pointing to variable y
ptr1 = &x; // Assign value (Store the address of x) in ptr1
cout << "The value in x is " << x << endl;
cout << "The address of x is " << ptr1 << endl;
ptr2 = ptr1; // Assign a pointer to another pointer
// Both pointers must be of the same type
// ptr2 is now pointing to variable x
cout << "The address in ptr1 is " << ptr1 << endl;
cout << "The address in ptr2 is " << ptr2 << endl;
return 0;
}
13
value in x
address of
address in
address in
is 25
x is 0x0012ff88
ptr1 is 0x0012ff88
ptr2 is 0x0012ff88
14
Assign value
Input/output operations
Arithmetic operations
Relational/logical expressions
15
Huruf
Nom
9
16
Huruf
Nom
10
Self test 1
1.
18
Self test 2
2.
p
p
q
q
p
=
=
=
=
=
&x;
&y;
&x;
&y;
q;
19
20
21
Exercises
22