0% found this document useful (0 votes)
6 views34 pages

IP 07 Pointer

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views34 pages

IP 07 Pointer

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Pointer

Inst. Nguyễn Minh Huy

Fundamentals of Programming - Nguyễn Minh Huy 1


Contents
 Pointer concept.
 Pointer usage.
 Pointer vs. array.
 Memory management.

Fundamentals of Programming - Nguyễn Minh Huy 2


Contents
 Pointer concept.
 Pointer usage.
 Pointer vs. array.
 Memory management.

Fundamentals of Programming - Nguyễn Minh Huy 3


Pointer concept
 Computer memory:
 RAM (R
(Random Access Memory). RAM (4GB)
0
 Primary vs. Secondary memory.
 Used to store:
 Operating system.
 Programs: variables + functions.

 Contains 1-
1-byte cells.
 RAM 4GB ~ 4 billion cells.
 Each cell has an address number.
 RAM 4GB address 0  232 – 1.
232

Fundamentals of Programming - Nguyễn Minh Huy 4


Pointer concept
 Variable address:
 How it works, when declaring a variable?
 Allocate a series of memory cells. int x;
 Assign variable name to the first cell.
65 66 67 68
 Number of cells?  variable type. x ? ? ? ?
 Variable address = address of first cell.
 How value is stored in variable?
 Divide value into bytes. x = 1057;
 Store each byte in cell. 65 66 67 68
 Start from the first cell. x 33 4 0 0

Fundamentals of Programming - Nguyễn Minh Huy 5


Pointer concept
 Address type in C:
 Store integer, real number?  int,
int, float type
type..
 Store variable address?  address type.
 Syntax: <type> *.*.
 Address of int:
int: int *.
 Operator &:
 Usage: get variable address. x = 1057;
 Syntax: &<variable name>; 65 66 67 68
int x = 1057; x 33 4 0 0
float y = 1.25;
int *address_x = &x; 91 92 93 94
float *address_y
*address_y = &y; address_x 65 0 0 0

Fundamentals of Programming - Nguyễn Minh Huy 6


Pointer concept
 Pointer in C:
 A variable having address type.
 Store address of other variable.
 Its value is an address number.
 Its size:
 Fix-
Fix-sized for all address type.
 Depend on platform:
 Intel 8008 (1972), 8-8-bit, 1 byte (256 B).
 Intel 8086 (1978), 16-
16-bit, 2 bytes (64 KB).
 Intel 80386 (1985), 32-
32-bit, 4 bytes (4 GB).
 Intel Core (2000), 64-
64-bit, 8 bytes (16 TB).

Fundamentals of Programming - Nguyễn Minh Huy 7


Contents
 Pointer concept.
 Pointer usage.
 Pointer vs. array.
 Memory management.

Fundamentals of Programming - Nguyễn Minh Huy 8


Pointer usage
 Pointer declaration:
 Declare variable having address type.
 Method 1:
<type> *<pointer name>;
int *p1; // Pointer storing address of int.
float *p2; // Pointer storing address of float.
 Method 2:
typedef <type> * <alias>;
<alias> <pointer name>;
typedef int * int_pointer
int_pointer;;
typedef float * float_pointer
float_pointer;;
int_pointer p1;
float_pointer p2

Fundamentals of Programming - Nguyễn Minh Huy 9


Pointer usage
 Pointer referencing:
 Pointer has random address at first  initialization.
 Operator &:
&: get variable address.
 Syntax: <pointer name> = &<variable>;
int x = 5;
int *p = &x;
 Pointer only accepts address of the same type!!
float y;
int *q = &y; // Wrong!!
 NULL address:
 Empty address  default initialization.
int *r = NULL
NULL;; // C, use <stdio.h
<stdio.h>>
int *s = nullptr
nullptr;; // C++, keyword

Fundamentals of Programming - Nguyễn Minh Huy 10


Pointer usage
 Pointer de-
de-referencing:
 Operator *:
 Read variable whose address pointer stores.
 Syntax: <variable> = *<pointer>;
int x = 5;
int *p = &x;
int k = *p;
*p; // get x value.
printf(“%d
printf (“%d\\n”, p); // print x address.
printf(“%d
printf (“%d\\n”, *p);
*p); // print x value.
printf(“%d
printf (“%d\\n”, &p);
&p); // print p address.
 Pointer points to variable whose address it stores!
72 73 74 75 91 92 93 94
x 5 0 0 0 p 72 0 0 0

Fundamentals of Programming - Nguyễn Minh Huy 11


Pointer usage
 Passing pointer to function: void foo
foo((int *g)
{
 Pass--by-
Pass by-value: *g = *g + 1;
 Pass copy of pointer to function. g=g+1
 Address stored in pointer is }
NOT CHANGED.
int main()
 Variable that pointer points to {
CAN BE CHANGED. int x = 5;
int *p = &x;
main()
72 73 74 75 foo(int *g) foo(
foo(p);
x 5 0 0 0 66 67 68 69 // x is changed.
g 72 0 0 0 }
91 92 93 94
p 72 0 0 0

Fundamentals of Programming - Nguyễn Minh Huy 12


Pointer usage
 Passing pointer to function: void foo
foo((int *&g)
*&g)
{
 Pass--by-
Pass by-reference (C++): *g = *g + 1;
 Pass real pointer to function. g=g+1
 Address stored in pointer }
CAN BE CHANGED.
int main()
 Variable that pointer points to {
CAN BE CHANGED. int x = 5;
int *p = &x;
main()
72 73 74 75 foo(
foo(p);
x 5 0 0 0 // x is changed.
// p is changed.
91 92 93 94 foo(int *&g) }
p 72 0 0 0 g

Fundamentals of Programming - Nguyễn Minh Huy 13


Pointer usage
 Pointer to struct
struct::
 Pointer stores address of struct variable.
 Declaration:
 Method 1: struct <struct type> *<pointer name>;
 Method 2: typedef struct <struct type> * <alias>;
<alias> <pointer name>;
struct Fraction
{
int numerator, denominator;
};
typedef struct Fraction * FractionPointer
FractionPointer;;

struct Fraction *p;


FractionPointer q;

Fundamentals of Programming - Nguyễn Minh Huy 14


Pointer usage
 Pointer to struct
struct::
 Access struct member through pointer:
 Method 1: (*<pointer
(*<pointer name>).
name>).<<struct member>;
 Method 2: <pointer name>-
name>-><struct member>;
struct Fraction f;
struct Fraction *p = &f;

(*p
(*p).numerator = 1;
p->denominator = 2;

Fundamentals of Programming - Nguyễn Minh Huy 15


Contents
 Pointer concept.
 Pointer usage.
 Pointer vs. array.
 Memory management.

Fundamentals of Programming - Nguyễn Minh Huy 16


Pointer vs. array
 Pointer as array:
 Array is a pointer.
 Stores address of first element.
int main()
{
int a[ 10 ] = { 1, 2, 3 };
printf(“%d
printf (“%d\\n”, a);
printf(“%d
printf (“%d\\n”, &a[0]
&a[0]);
); // a = &a[0].
}
a[0] a[1] a[2]
72 73 74 75 76 77 78 79 80 81 82 83
a 1 0 0 0 2 0 0 0 3 0 0 0 …

Fundamentals of Programming - Nguyễn Minh Huy 17


Pointer vs. array
 Pointer to array element:
 To access array indirectly.
 Consider the following code:
int a[100] = { 1, 2, 3 };
int *p = a;
a; // p = &a[0]
*p = *p + 1;
printf(“%d
printf (“%d\\n”, *p);

a[0] a[1] a[2]


72 73 74 75 76 77 78 79 80 81 82 83
a 1 0 0 0 2 0 0 0 3 0 0 0 …

44 45 46 47
p 72 0 0 0

Fundamentals of Programming - Nguyễn Minh Huy 18


Pointer vs. array
 Pointer increment/decrement:
 Pointer value changed based on pointer type.
 Jumping formula:
 <Pointer> +/ +/-- k = <Address> +/
+/-- k * sizeof(<Pointer
sizeof(<Pointer Type>).
Type>).
int a[100] = { 1, 2, 3 };
int *p = a;
a;
printf(“%d
printf (“%d\\n”, *(p + 1) );
printf(“%d
printf (“%d\\n”, *(p + 2) );
a[0] a[1] a[2]
72 73 74 75 76 77 78 79 80 81 82 83
a 1 0 0 0 2 0 0 0 3 0 0 0 …

44 45 46 47 p+1 p+2
p 72 0 0 0

Fundamentals of Programming - Nguyễn Minh Huy 19


Pointer vs. array
 Operator [ ]:
 Read memory content pointer jumps to.
 Syntax: <Pointer>[ <Index> ] ~ *(<Pointer> + <Index>)
int a[100] = { 1, 2, 3 };
int *p = a;

a[2] = 5;
*(a + 2) = 5;
*(p + 2) = 5;
p[2] = 5;

Fundamentals of Programming - Nguyễn Minh Huy 20


Pointer vs. array
 Passing array to function:
 Not passing whole array.
 Only passing address of first element.

 Pass pointer points to first element.


void printArray
printArray((int a[ ],], int n) {
for (int
(int i = 0; i < n; i++)
printf(“%d
printf (“%d “, *(a++) ); // Same as a[ i ]…
}
int main() {
int a[100];
printArray((a, 100);
printArray
for (int
(int i = 0; i < n; i++)
printf(“%d
printf (“%d “, *(a++) ); // Wrong, why?
}

Fundamentals of Programming - Nguyễn Minh Huy 21


Contents
 Pointer concept.
 Pointer usage.
 Pointer vs. array.
 Memory management.

Fundamentals of Programming - Nguyễn Minh Huy 22


Memory management
 Memory allocation (library <stdlib.h
<stdlib.h>):
>):
 Request memory from RAM.
 malloc(( <number of bytes> ).
malloc
 Return: allocated memory address or NULL (failed).
int *p = ( int * ) malloc
malloc(( 3 * sizeof(
sizeof( int ) );
Fraction *q = ( Fraction * ) malloc
malloc(( 2 * sizeof
sizeof(( Fraction ) );

44 45 46 47 72 73 74 75 76 77 78 79 80 81 82 83
p 72 0 0 0 ? ? ? ? ? ? ? ? ? ? ? ?
p+1
numerator denominator numerator denominator
33 34 35 36 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
q 55 0 0 0 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
q+1

Fundamentals of Programming - Nguyễn Minh Huy 23


Memory management
 Memory allocation:
 calloc(( <block count>, <block size> ).
calloc
 Return: allocated memory address or NULL (failed).
int *p = ((int
int *) calloc
calloc(( 3, sizeof(
sizeof(int)
int) );
Fraction *q = (Fraction *) calloc
calloc(( 2, sizeof(Fraction)
sizeof(Fraction) );
 malloc vs. calloc
calloc??
 realloc(( <allocated address>, <bytes> ).
realloc
 Resize allocated memory.
 Return: resized memory address or NULL (failed).
int *p = ((int
int *) malloc
malloc(( 2 * sizeof(
sizeof(int)
int) );
p[ 0 ] = 5;
int *q = ((int
int *) realloc
realloc(( p, 4 * sizeof(
sizeof(int)
int) );

Fundamentals of Programming - Nguyễn Minh Huy 24


Memory management
 Memory de-
de-allocation (library <
<stdlib.h
stdlib.h>):
>):
 Return memory to RAM after use.
 Memory leak problem:
 Declared variables are auto return.
 Allocated memory ARE NOT auto return.
 Forget to return  memory leak.
 free( <pointer> ).
float *p = ( float * ) malloc
malloc(( 20 * sizeof
sizeof(( float ) );
free( p );
p = NULL; // Safe practice.

Fundamentals of Programming - Nguyễn Minh Huy 25


Memory management
 C++ memory management:
 Is compatible with C (malloc
(malloc,, calloc,
calloc, realloc,
realloc, free).
 Has new way to manage memory.
 Operator new
new:: allocate memory.
 Syntax: new <type>
<type>[[<number of elements>]
elements>];
 Return: address of allocated memory.
 Operator delete
delete:: de-
de-allocate memory.
 Syntax: delete <pointer>;
int *p = new int [ 10 ];
Fraction *q = new Fraction [ 30 ];
delete [ ]p;
delete [ ]q;

Fundamentals of Programming - Nguyễn Minh Huy 26


Memory management
 Dynamic 1-
1-D array:
 Array has flexible size:
 Use pointer.
 Allocate memory as needed.
 De-
De-allocate when finish.
 Use memory more efficient.
void inputArray
inputArray(( int *&a*&a,, int &n ) { int main()
printf(“Enter
printf (“Enter number of elements: “); {
scanf(“%d”,
scanf (“%d”, &n);
&n); int *a;
*a;
a = new int [ n ]; int n;
for (int
(int i = 0; i < n; i++) {
printf(“Enter
printf (“Enter element %d:”, i); inputArray(a, n);
inputArray(a,
scanf(“%d”,
scanf (“%d”, &a[ i ]); delete [ ]a
]a;
} }
}

Fundamentals of Programming - Nguyễn Minh Huy 27


Summary
 Pointer concept:
 Each variable has a memory address.
 Pointer is variable storing other variable address.
 Pointer usage:
 Declaration: <Data type> *.
 Referencing (operator &): points to memory address.
 De-
De-referencing (operator *): read memory content.

Fundamentals of Programming - Nguyễn Minh Huy 28


Summary
 Pointer vs. Array:
 Array is a pointer pointing to first element.
 Operator [ ]: jump and de-
de-reference.
 Array argument is pointer passed to function.
 Memory management:
 Allocation: malloc
malloc,, calloc,
calloc, realloc.
realloc.
 De-
De-allocation: free.
 Memory leak: allocated memory not returned.
 C++:
 Allocation: operator new.
 De-
De-allocation: operator delete.

Fundamentals of Programming - Nguyễn Minh Huy 29


Practice
 Practice 7.1:
Given the following code:
int main()
{
int *x, y = 2;
float *z = &y;

*x = *z + y;
printf(“%d”,
printf (“%d”, y);
}
a) Fix error of the code.
b) After fixing, what is displayed on screen?

Fundamentals of Programming - Nguyễn Minh Huy 30


Practice
 Practice 7.2:
Explain the difference amongst the following 3 functions:
void swap1(int
swap1(int x, int y) void swap3(int
swap3(int *x, int *y)
{ {
int temp = x; int temp = *x;
x = y; *x = *y;
y = temp; *y = temp;
} }

void swap2(int
swap2(int &x, int &y)
{
int temp = x;
x = y;
y = temp;
}

Fundamentals of Programming - Nguyễn Minh Huy 31


Practice
 Practice 7.3:
Explain what the following program prints:
int main()
{
double m[100];
double *p1, *p2;

p1 = m;
p2 = &m[6];
printf(“%
printf (“%lld
lld”,
”, p2 – p1);
}

Fundamentals of Programming - Nguyễn Minh Huy 32


Practice
 Practice 7.4:
Explain what the following program prints:
#include <stdio.h
<stdio.h>>

int main()
{
int x = 1023;
char *p = (char *)&x;

printf(“%d
printf (“%d %d %d %d
%d\\n”, p[0], p[1], p[2], p[3]);
}

Fundamentals of Programming - Nguyễn Minh Huy 33


Practice
 Practice 7.5:
Write C/C++ program to use pointer as dynamic array:
- Enter an array of N fractions.
- Delete fractions having duplicate values (keep the first one).
- Print the result array.
Input format:
Number of fractions = 5
Fraction 0 = 1/2
Fraction 1 = 2/5
Fraction 2 = 4/8
Fraction 3 = 9/7
Fraction 4 = 18/14
Output format:
1/2 2/5 9/7

Fundamentals of Programming - Nguyễn Minh Huy 34

You might also like