Bài giảng Introduction to Computer Programming (C language) - Chapter 8: Pointers - Võ Thị Ngọc Châu
Content
Introduction
Declare and initialize pointers
Operations on pointers
Pointers and arrays
Variable storage and heap memory
Memory allocation and de-allocation
Pointers and structures
Pass pointers to a function
Function pointers
Summary
Trang 1
Trang 2
Trang 3
Trang 4
Trang 5
Trang 6
Trang 7
Trang 8
Trang 9
Trang 10
Tải về để xem bản đầy đủ
Bạn đang xem 10 trang mẫu của tài liệu "Bài giảng Introduction to Computer Programming (C language) - Chapter 8: Pointers - Võ Thị Ngọc Châu", để tải tài liệu gốc về máy hãy click vào nút Download ở trên
Tóm tắt nội dung tài liệu: Bài giảng Introduction to Computer Programming (C language) - Chapter 8: Pointers - Võ Thị Ngọc Châu
Attemps to resize the memory block pointed to by ptr that was previously allocated with a call to malloc or calloc De-allocation void free(void* ptr) De-allocates the memory previously allocated by a call to calloc, malloc, or realloc 43 Define an array of 5 integer numbers in heap memory Allocation Check if OK Allocation Check if OK USE De-Allocation De-Allocation 44 Memory allocation and de-allocation Type casting The number of bytes to be allocated for the appropriate data type of = the number of memory units * memory unit size each value in a memory unit Type casting The number of Memory unit size for the appropriate data type of memory units each value in a memory unit 5 memory units Memory to be allocated An integer value ? ? ? ? ? Memory unit size of an integer 4 bytes 4 bytes 4 bytes 4 bytes 4 bytes = 4 bytes Memory allocation and de-allocation Memory layout Stack pA pB i ? Zero-filled Heap ? ? ? ? ? 0 0 0 0 0 bytes with calloc Uninitialized data .bss Initialized data .data Code .text 46 Calculate an averaged grade of the courses you have taken. It is noted that the number of courses might be different from student to student. 47 Memory allocation and de-allocation Define an array of integer numbers in the stack: a[i] Define an array of integer numbers in the heap: *(pA+i) 48 Memory allocation and de-allocation A static array not in heap Memory layout Stack a 1 2 3 4 5 pA i ? A dynamic array in heap Heap ? ? ? ? ? Uninitialized data .bss Initialized data .data Code .text 49 Memory allocation and de-allocation What are the differences? A static array A dynamic array Allow initialization at No initialization at declaration of array declaration of pointer Access via array name Access via pointers Possible addresses Possible indices from zero Located not in the heap Located in the heap Fixed size thru existence Varying size with realloc No extra storage Extra storage for pointer No need to free the Need to free the memory memory location location via pointer sizeof(array name): sizeof(pointer): pointer array size in bytes size, not array size 50 Memory allocation and de-allocation Strings are one-dimension arrays of characters ended by „\0‟. Strings can be dynamically allocated in the heap memory via pointers. The length of a string is not required to be known in advance. The length of a string can be varied. Allocation: One extra byte is needed for „\0‟. Use: char* aString; Instead of: char aString[10]; or char aString[] = “a string”; 51 s3: a pointer points to an array of characters ended by „\0‟ in the heap a dynamic string: an array of characters ended by „\0‟ in the heap (char*)calloc(length+1, sizeof(char)) s3: a pointer points to a dynamic string a dynamic string: resized in the heap (char*)realloc(pointer, (length+1)*sizeof(char)) char s1[] = “Computer”; char s2[] = “Programming”; Generate s3 as a concatenation of s1 and s2. If s3 does not contain “: C language”, then extend s3 with “: C language” at the end.52 Check if a string sub is a substring of a string aStr: int isSubstring(const char sub[], const char* aStr); sub = “:C language” aStr = “Computer Programming” isSubstring(sub, aStr) returns 0. sub = “:C language” aStr = “Computer Programming: C language” isSubstring(sub, aStr) returns 1. 53 Memory allocation and de-allocation Multidimensional arrays in the heap Generate a dynamic random matrix RxC of integer numbers in the range of [0, 100) R and C corresponding to the number of rows and the number of columns input by a user R = 3, C = 4 m m[0] 0 2 7 32 m[1] 3 9 11 27 m[2] 71 54 6 80 int** m; int* m[0]; int m[0][0]; int* m[1]; int m[0][1]; int* m[2]; int m[2][3]; 54 R = 3, C = 4 m m[0] 0 2 7 32 m[1] 3 9 11 27 A pointer to the matrix: pointer to pointer m[2] 71 54 6 80 Memory allocation Memory allocation for pointers to for the elements rows in each row Generate a dynamic random matrix RxC of integer numbers in the range of [0, 100) De-allocate the memory location of each row 55 De-allocate the memory location of pointers to rows Memory allocation and de-allocation Multidimensional arrays in the heap Enter the names of your courses. Your course list might be different from your friend‟s. Check if any course is input more than once. If yes, simply ignore the duplicate. char** yrCourse; yrCourse n = course# = 4 yrCourse[0] P r o g r a m m i n g \0 yrCourse[1] M a t h s \0 yrCourse[2] P h y s i c s \0 yrCourse[3] C h e m i s t r y \0 char* yrCourse[0]; char yrCourse[0][0]; char* yrCourse[3]; char yrCourse[3][6]; 56 Enter the names of your courses. Your course list might be different from your friend‟s. A pointer to an array of strings: pointer to pointer Check if any course is input more than once. If yes, simply ignore Allocate the the duplicate. memory location of the pointers to strings Allocate the memory location of each string Deallocate the memory location of each string Deallocate the memory location of the pointers to strings Memory allocation and de-allocation Problems with dynamic memory allocation Multiple allocations for a single pointer Allocation with no explicit de-allocation At multiple levels of details in case of pointers to pointers sizeof(pointer) for the number of allocated bytes Reference to the de-allocated memory location A pointer type for a return type of a function Missing one extra byte for „\0‟ in dynamic strings ... 58 struct Data Type - Recall struct { struct point { struct student { int x; int x; char IdStudent[10]; int y; int y; char Name[50]; }; }; int IdMajor; int EntranceYear; struct point Location; }; Structure declaration struct { struct point { struct student aStudent; int x; int x; int y; int y; } aPoint1, aPoint2; } aPoint4, aPoint5; struct { struct point aPoint6 = {0, 0}; int x; int y; } aPoint3 = {0, 0}; Variable declaration aStudent.EntranceYear Member aPoint3.x aPoint6.y 59 aStudent.Location.x access Pointers and structures A structure is a collection of one or more variables grouped together under a single name for convenient handling. Memory layout of variable aPoint3 struct { aPoint3 int x; x 0 4 bytes for int int y; y 0 4 bytes for int } aPoint3 = {0, 0}; aPoint3.x returns 0, an int value of member x; aPoint3.y returns 0, an int value of member y; &aPoint3.x returns an address of member x; &aPoint3.y returns an address of member y; &aPoint3 returns an address of the variable aPoint3; 60 Pointers and structures An array of structures A group of contiguous memory locations of a struct data type struct { pointArray int x; x ? ? ? int y; y ? ? ? } pointArray[3]; pointArray[0] pointArray[1] pointArray[2] pointArray[0].x returns an int value of member x of the first element of array; pointArray[0].y returns an int value of member y of the first element of array; &pointArray[0].x returns an address of member x of the first element of array; &pointArray[0].y returns an address of member y of the first element of array; &pointArray[0] returns an address of the first element of array; &pointArray[1] returns an address of the second element of array; 61 Pointers and structures A pointer to a structure A variable whose value is an address of a memory location of a struct data type struct { aPoint3 int x; x 0 pPoint int y; y 0 } * pPoint = &aPoint3; pPoint returns an address of the variable aPoint3; *pPoint returns a structure value of the variable aPoint3; (*pPoint).x returns 0, an int value of member x; (*pPoint).y returns 0, an int value of member y; &(*pPoint).x returns an address of member x; &(*pPoint).y returns an address of member y; 62 Pointers and structures A pointer to a structure A variable whose value is an address of a memory location of a struct data type struct { aPoint3 int x; x 0 pPoint int y; y 0 } * pPoint = &aPoint3; Equivalent access: pPoint->x (*pPoint).x or pPoint->y (*pPoint).y Use -> for access of a pointer to a member of a structure: pointer->member_of_structure 63 Pointers and structures Given 5 locations, randomly select one location and then print the selected location and its farthest locations struct location { aLoc float x; x 1.50 2.00 4.00 5.00 2.00 pSel float y; y 3.00 1.70 3.10 6.30 1.10 }; aLoc[0] aLoc[1] aLoc[2] aLoc[3] aLoc[4] struct location aLoc[n] = {{1.5, 3}, {2, 1.7}, {4, 3.1}, {5, 6.3}, {2, 1.1}}; struct location* pSel = NULL; pSel->x returns 2.00. pSel = &aLoc[4]; pSel->y returns 1.10. 64 Given 5 locations, randomly select one location and then print the selected location and its farthest locations Access to member of a structure via an element of array: . Access to member of a structure via pointer: -> 65 Pointers and structures Dynamic structures in the heap memory Single structure Array of structures Given n locations, find the nearest locations from your current location. A pointer to an array A pointer to a of structures in heap structure in heap struct location * aLoc, * curLoc; aLoc = (struct location*) calloc(n, sizeof(struct location)); curLoc = (struct location*) calloc(1, sizeof(struct location)); 66 Given n locations, find the nearest locations from your current location. 67 Calculate an averaged grade of the courses you have taken. It is noted that the number of courses might be different from student to student. 68 Pass pointers to a function Address passing to a function Allow call-by-reference Allow multiple input values like arrays Avoid huge data copy Allow multiple returned values Pointers are passed to a function: Pointers Pointers to pointers 69 Pass pointers to a function Swap a and b: Address passing via variables‟ addresses Address passing via pointers that point to the variables 70 Give an array of n integer numbers, calculate theirPass mean pointers and standard to a deviation. function A pointer to an array of the int values The number of elements in the array A pointer to a float memory location for the expected output: standard deviation Address passing with A pointer to a float memory location a, &mean, &sdev for the expected output: mean 71 Given n locations (randomly generated) A pointer to the array and a current location, check if the of structures location current location has already been in the list of n locations. If not, insert the current location into the given list. A pointer to the variable n as the number of elements in the array might be changed 72 Given n locations (randomly generated) and a current location, check if the current location has already been in the list of n locations. If not, insert the current location into the given list. 73 MATRIX MULTIPLICATION: mulM = aMxbM - Sizes of aM and bM are given. - Elements of aM and bM are randomly generated. NOTE: - Pointers to matrices are passed to the functions. - Pointers to matrices are returned from the functions. 74 Function for matrix multiplication: res = m1xm2 75 Function for generating a matrix m with size rxc 76 Functions for inputting a natural number and printing a matrix 77 Function pointers Function name is the starting address of the function memory where the code that performs the function‟s task exists. A function pointer is a pointer that points to the function memory location. Containing an address of the function in memory Able to be passed to functions, returned from functions, stored in arrays, assigned to other function pointers in initialization A means for the flexible execution of the program when calling functions via function pointers instead of their function names 78 Function pointers Declaration based on function prototype return_type (*pointer_name)(argument_list) =opt initial_valueopt; - pointer_name: an identifier for a pointer that points to a function - return_type: a data type of the returned value of the function - argument_list: list of arguments (specifically data types) separated by comma for formal parameters of the function Values for initialization and assignment NULL Function names Function pointers Function call through a function pointer instead of a function name 79 Function pointers Declaration based on function prototype return_type (*pointer_name)(argument_list) =opt initial_valueopt; int add(int a, int b); int (*op)(int, int) = add; int sub(int a, int b); int (*opList1[])(int, int) = {add, sub, mul}; int mul(int a, int b); int (*opList2[2])(int, int) = {add, sub}; A function call to add function: add(1, 2); (*op)(1, 2); op(1, 2); (*opList1[0])(1, 2); opList1[0](1, 2); (*opList2[0])(1, 2); opList2[0](1, 2); 80 A text-based menu-driven program for calculation of two integer numbers An array of function pointers A call to an appropriate function via a function pointer in the array of function pointers 81 Function definitions for addition, subtraction, multiplication, division, and remainder corresponding to (*maths[0])(int, int), (*maths[1])(int, int), (*maths[2])(int, int), (*maths[3])(int, int), (*maths[4])(int, int) 82 Print a matrix Function pointers A formal parameter is a function pointer print: - Input: an array of integer numbers and an integer number - Output: void Address of a function is passed as an actual parameter in function call Call a function through a function pointer instead of its name 83 Summary Pointers Support for manipulation on physical memory Simulation for pass-by-reference Enabling dynamic data structures in heap memory On demand Size-varying Allocation: calloc, malloc, realloc De-allocation: free 84 Summary Operations on pointers Addresses vs. non-address values Pointers and arrays, structures, functions Pointers and other issues Constant Pointers to void Pointers to pointers Dangling references Function pointers 85 Chapter 8: Pointers 86
File đính kèm:
- bai_giang_introduction_to_computer_programming_c_language_ch.pdf