Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 37

Kỹ Thuật Lập Trình

Khang Q.H. Vo (M.Sc.)


FIT - IUH
CON TRỎ - Pointers
NỘI DUNG
1. Address in C (Lưu trữ dữ liệu trong RAM)
2. Sơ đồ bộ nhớ (Memory Map of a program)
3. Giải thích con trỏ là gì?
4. Các phép toán trên con trỏ
5. Truyền tham số là con trỏ
6. Con trỏ và mảng 1 chiều
7. Cấp phát động

Pointers 3
1. Address in C

Pointers 4
Address in C - Example

Pointers 5
Where can we put program’s data?

High Data Common Variables


address Segment All functions can access them
0x0000FFFF Code
Global
Segment

Data Dynamic
Dynamic allocated data through
Heap explicitly statements for memory
allocation

Local
Variables are defined in functions.
They will exist only when the
Stack
function is executed and they will
Segment
Low address be removed when the function
0x00000000 Completed execution

Pointers 6
2. Memory Map of a program

MAXN=10
Data segment 4202496

Code of
Code 4199199 main()
segment
Code of
4199056 average()

HEAP

2293620 a=5
2293616 b =5
2293612 c =8
STACK
segment
2293576 c=8
2293572 b =5
2293568 a =5
2293552 t = 6.0000

Pointers 7
3. What is a Pointer?
 Con trỏ là một biến, chứa địa chỉ của một biến khác.
 Xét đoạn code:
int a = 9;
int *p = &a;

Pointers 8
3. What is a Pointer?
address value
 Con trỏ là một biến, chứa địa chỉ của một vị 80000 32
trí bộ nhớ của một biến khác
p2: 80000
 Nếu một con trỏ chứa địa chỉ của biến khác,
được gọi là trỏ đến biến. 400 7

p1: 400
 Con trỏ cung cấp một phương thức gián tiếp để truy
cập giá trị của biến.
 Con trỏ có thể trỏ đến các biến của các loại dữ liệu cơ bản khác
như int, char hoặc double hoặc tổng hợp dữ liệu như mảng
hoặc cấu trúc.

Pointers 9
4. Pointer Variables
Syntax: dataType *name;

Examples:
int *pI;
double* pD;
char *pC;

Pointers 10
Con trỏ có kiểu khác nhau thì có gì khác khau ?

• Về bản chất, tất cả con trỏ dù là char* hay int* đều là số nguyên và kích
thước của chúng đều bằng kiểu int.

Pointers 11
Con trỏ có kiểu khác nhau thì có gì khác khau ?

• Sự khác nhau nằm ở số byte khi truy cập vùng nhớ


• Xét đoạn code:

• p và q đều cùng trỏ đến byte đầu tiên của biến n.


• Tuy nhiên, khi truy cập đến vùng nhớ thông qua con trỏ, con
trỏ char *p chỉ đọc 1 byte, còn con trỏ int *q sẽ đọc 4 byte

Pointers 12
5. Pointer Operators
How to Operator Example
Get address of a variable & int n= 7;
and assign it to a pointer int* pn = &n;
Access indirectly value of * *pn =100;
a data through it’s pointer

10000 n=7 10000 n = 7  100


9996 pn 9996 pn = 10000
int n= 7; *pn = 100;
int* pn = &n; *pn = 100;  Value at [10000]
pn = &n;  =100
pn=10000

Pointers 13
Pointer Operators…
2293620 n=7
2293616 pn= 2293620
2293612 ppn= 2293616

n  int  pn stores address of n


 pn: int*
pn  int*  ppn stores address of pn
 ppn: (int*)*  ppn: int**

Pointers 14
Pointer Operators… Walkthrough
100 n=7  54
*pn = 2*(*pm) + m*n;
96 m=6  -30
Value at 100 = 2*(value at 96) + m *n
92 pn=100
Value at 100 = 2*6 + 6 *7
88 pm= 96
Value at 100 = 12 + 42 = 54

*pm += 3*m - (*pn);


Value at 96 += 3*6 – value at 100
Value at 96 += 3*6 – 54
Value at 96 += 18 – 54
Value at 96 += (-36)
Value at 96 = 6+ (-36) = -30

15

Pointers
Walkthroughs: Do yourself

int n=7,m=8; int n=7, m=8;


int* p1= &n, *p2=&m; int* p1= &n, *p2=&m;
*p1 +=12-m+ (*p2); *p1 +=5 + 3*(*p2) –n ;
*p2 = m + n- 2*(*p1); *p2 = 5*(*p1) – 4*m + 2*n;
printf(“%d”, m+n); What are values of m and n?
What is the output?

Pointers 16
6. Pointer Arithmetic Operators:
+, -, ++, --
Pointer +i  Pointer + (i*sizeof(baseType))

2293632

2293624

x
2293616
2293612
2293608 2293608
n 2293604
2293600 2293600
2293596

Pointers 17
Pointer Arithmetic Operators :
Accessing the neighbor

/* file pointer_demo4.c */
#include <stdio.h>
int main()
Copy and paste, run the { int n2= 10;
int n1= 6;
program, explain the int n0= 5;
result. printf("n2=%d, n1=%d, n0=%d\n", n2, n1, n0);
int* p = &n1;
*p=9;
p++;
*p=15;
p--;
p--;
*p=-3;
printf("n2=%d, n1=%d, n0=%d\n", n2, n1, n0);
return 0;
}

Pointers 18
Exercises
double *p;
Suppose that a double occupies the memory block of 8 bytes and
p stores the value of 1200.
What are the result of the following expression? p+8 p-3 p++
long*p;
Suppose that a long number occupies the memory block of 4 bytes
And p stores the value of 1000.
What are the result of the following expression? p+8 p-3 p++

char*p;
Suppose that a character occupies the memory block of 1 byte
and p stores the value of 207000.
What are the result of the following expression? p+8 p-3 p++

Pointer +i  Pointer + (i*sizeof(baseType))

Pointers 19
7. Pointers as Parameters of a Function

• C uses by-value parameters only  A function can


not modify values of arguments.
• To modify values of arguments, pointers as
parameters of a function are used.

22
7. Pointers as Parameters of a Function
• C passes arguments to parameters by values only
 C functions can not modify outside data.

y = 7 5
x=57
t =5

a =5
b =7

Pointers 23
7. Pointer as Parameters of a Function …
Use pointer arguments, we can modify outside values.

py: 996
px : 1000
t =5

1000 a =57
996 b =75

Pointers 24
Functions with pointers as
parameters
Review: Pass by-value Parameters
65518
65510
R1=3
R2=8
X 65502 R3=9

stack
65494 r3=9 segment
65486 r2=8
65478 r1=3
65466 t=1.75…

Heap

main
867 code
code
segment
CalcImp
706 code

172 pi=3.14.. Data


170 maxN=100 segment

25
7. Pointers as parameters: Demo

1000 x=9.08
main
992 y=-12.34

p1: 1000
p2: 992 swapDouble
t

swapDouble(&x, &y);

26
7. Pointers as parameters: Demo

1000 x=9.08
main
992 y=-12.34

p1: 9.08

p2: -12.34 swapDouble2

27
8. Pointers and Arrays
Data segment 4202496 20
The name of the array is the code
Code segment 4199056
address of the first element.

80
Heap
bytes
4072496

Stack segment 20
a1: 2293584 bytes
a2:2293580 4072496

28
Array Function Parameter: Demo

Contiguous Storage 29
Array Function Parameter: Demo
2.
x=3 n=0  1

0
3

x=7 n=3 4

0 1 2
3 5 2

Contiguous Storage 30
9. Dynamic Allocated Data
Stdlib.h Data
void* malloc (size_t numBytes) ; Segment
void* calloc (size_t numberOfItem, size_t bytesPerItem) Code
void* realloc (void* curPointer, size_t newNumBytes); Global
Segment
void free(void* willBeDeletedPointer);

Examples Data Dynamic


int* p = (int*) malloc (sizeof (int)) ; Heap
*p=2;
calloc: Contiguous Allocation
….
free(p);
malloc: Memory allocation Local
realloc: Re allocation
Stack
size_t: Another name of the int type. It is used in case of Segment
memory allocation managing.
void is the general datatype which means that the data type is
not determined yet. So, user must give an explicit casting
when it is used.

Pointers 31
Demo: Dynamic Allocated Data

/* file pointer_demo5.c */
#include <stdio.h>
#include <stdlib.h>
const int MAXN =100;
int main()
{
int n; int *p1; int *p2; int *p3;
(1) Copy, past, compile and run the
printf("Address of MAXN: %u\n", &MAXN); program.
printf("Main function ia allocated at: %u\n", &main); (2) Draw the memory map.
printf("Address of n : %u\n", &n);
printf("Address of p1: %u\n", &p1);
(3) Show that where is data
printf("Address of p2: %u\n", &p2); segment, code segment, stack
printf("Address of p3: %u\n", &p3); segment and heap of the program.
p1 = (int*)malloc(sizeof(int));
p2 = (int*)malloc(sizeof(int));
(4) Give comment about the
p3 = (int*)malloc(sizeof(int)); direction of dynamic memory
printf("Dynamic allocation (p1) at: %u\n", p1); allocation.
printf("Dynamic allocation (p2) at: %u\n", p2);
printf("Dynamic allocation (p3) at: %u\n", p3);
free(p1);
free(p2);
return 0;
}

Pointers 32
Dynamic Allocated Data- Do yourself
Use dynamic memory allocation. Develop a program that will accept two real
numbers then sum of them, their difference, their product, and their quotient
are printed out.

/* main() */
double *p1, *p2;
p1 = (double*) malloc ( sizeof(double)); (1) Run this program
p2 = (double*) malloc ( sizeof(double)); (2) Draw the memory map
printf("p1, address: %u, value: %u\n", &p1, p1); (stack, heap).
printf("p2, address: %u, value: %u\n", &p2, p2);
printf("Input 2 numbers:");
scanf( "%lf%lf", p1, p2);
printf("Sum: %lf\n", *p1 + *p2);
printf("Difference: %lf\n", *p1 - *p2);
printf("Product: %lf\n", *p1 * (*p2));
printf("Quotient: %lf\n", *p1 / *p2);

Pointers 33
Dynamic Allocated Data- Do yourself

Write a C program using dynamic allocating memory to allow user entering


two characters then the program will print out characters between these in
ascending order.
Example:
Input: DA - char* pc1, *pc2;
-Cấp bộ nhớ pc1, pc2;
Output: - Nhập 2 ký tự vào pc1, pc2
A 65 81 41 - Nếu (*pc1>*pc2) Hoán vị *pc1, *pc2;
B 66 82 42 -char c;
-For (c= *pc1; c<=*pc2; c++)
C 67 83 43 - printf(“%c,%4d,%4o%4X\n”, c,c,c,c);
D 68 84 44

After the program executes, draw the memory map of the program.

Pointers 34
Summary
• Review the memory structure of a program
• Where can we put program’s data?
• What are pointers?
• Pointer Declarations
• Where are pointers used? Q&A
• Pointer operators
• Assign values to pointers
• Access data through pointer
• Explain pointer arithmetic
• Explain pointer comparisons
• Pointers as parameters of a function
• Dynamic Allocated Data
Pointers 35
Extra Walkthroughs with
functions
•Study the following C-function:
int t (int x, int y, int z)
{ int k= 2*x + 3*y + 5*z;
return k%13;
}
Suppose the above function is used in the following code:
int a=7, b=6, c=5;
int L= t(b,a,c);
What is the value of the L variable after this code is
executed?
Pointers 36
Extra Walkthroughs with
functions
•Study the following C-function:
void T (int * p, int*q)
{ int t= *p; *p=*q; *q=t;
}
Suppose the above function is used in the following code:
int a=7, b=6;
T(&a,&b);
What are the values of the a and b variables after this code is
executed?

Pointers 37
Extra Walkthrough with
functions
•Study the following C-function:
int T (int * p, int*q)
{ int t= (*p) + (*q) > 12 ? 5:6;
return 2*t%5;
}
Suppose the above function is used in the following code:
int a=3, b=4, c;
c= T(&a,&b);
What is the value of the c variable after this code is
executed?

Pointers 38
39

You might also like