Introduction to Computer Programming (C language) - Chapter 8: Pointers - Võ Thị Ngọc Châu

pdf 86 trang Gia Huy 17/05/2022 2710
Bạn đang xem 20 trang mẫu của tài liệu "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 bạn click vào nút DOWNLOAD ở trên

Tài liệu đính kèm:

  • pdfintroduction_to_computer_programming_c_language_chapter_8_po.pdf

Nội dung text: Introduction to Computer Programming (C language) - Chapter 8: Pointers - Võ Thị Ngọc Châu

  1. Ho Chi Minh City University of Technology Faculty of Computer Science and Engineering Chapter 8: Pointers Introduction to Computer Programming (C language) TS. Võ Thị Ngọc Châu (chauvtn@cse.hcmut.edu.vn, chauvtn@hcmut.edu.vn) 2017 – 2018, Semester 2
  2. Course Content C.1. Introduction to Computers and Programming C.2. C Program Structure and its Components C.3. Variables and Basic Data Types C.4. Selection Statements C.5. Repetition Statements C.6. Functions C.7. Arrays C.8. Pointers C.9. File Processing 2
  3. References [1] “C: How to Program”, 7th Ed. – Paul Deitel and Harvey Deitel, Prentice Hall, 2012. [2] “The C Programming Language”, 2nd Ed. – Brian W. Kernighan and Dennis M. Ritchie, Prentice Hall, 1988 and others, especially those on the Internet 3
  4. 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 4
  5. Introduction - Recall - Chapter 2 Main memory is addressable continuously. scanf() for input data from input devices to main memory Input a string: Input Input a character: A Input an integer: -123 Input device = keyboard Input device = keyboard Input device = keyboard Input A -123 Input A -123 Main memory ≈ variable Main memory ≈ variable Main memory ≈ variable Varying size: user-predefined Fixed sizes: character = 1 byte, integer = 4 bytes, char aString[5]; char aChar; int anInteger; scanf(“%s”, aString) scanf(“%c”, &aChar) scanf(“%d”, &anInteger) printf(“%s”, aString) printf(“%c”, aChar) printf(“%d”, anInteger)
  6. Introduction - Recall - Chapter 3 Built-in data types (primitive/fundamental)  char (signed char), unsigned char  short int, unsigned short, int, unsigned int, long int, unsigned long int, long long int, unsigned long long  float, double, long double  void  enum (enumerated data associated with integers) Derived data types We haven‟t discussed  arrays [] of objects of a given type this derived data type  pointers * to objects of a given type in detail yet!!!  structures struct containing objects of other types  union containing any one of several objects of various types 6
  7. Introduction - Recall - Chapter 3 Name Operator Description Example sizeof sizeof(type), Returns the size (bytes) of sizeof(char) sizeof(variable) a type or a variable int anInt = 0; sizeof(anInt); address &Variable Returns the address of the char aChar; memory named Variable char* ptrChar; ptrChar = &aChar; Dereferencing *Pointer Returns the value of the aChar = *ptrChar + 1; memory Pointer points to Index Variable[ ] Returns the element at the int intArray[3]; index intArray[0] = 0; intArray[1] = 1; intArray[2] = 2; anInt = intArray[1]; Structure Structure_ Refers to a member of a struct point pt; member name.member particular structure pt.x = 10; 7
  8. Introduction - Recall - Chapter 6 A function to swap two integer numbers void swap(int a, int b){ int temp; a and b will be passed by temp = a; values of int type. a = b; b = temp; } void swap(int *a, int *b){ int temp; temp = *a; a and b will be passed by pointers *a = *b; to int values, i.e. addresses of the memory that contains int values. *b = temp; } 8
  9. Introduction - Recall - Chapter 6 Stack‟s values when a=10 and b=9 in the main() function Caller‟s stack Callee‟s stack 000000000022FE4C 10 a &a 000000000022FE4C a 000000000022FE48 &b 9 b 000000000022FE48 b temp Stack‟s values before the callee ends Caller‟s stack Callee‟s stack 000000000022FE4C 9 a &a 000000000022FE4C a 000000000022FE48 &b 10 b 000000000022FE48 b 10 temp 9
  10. Introduction - Recall - Chapter 7 int a[10] = {2, 3, -1, 0, 4, 7, 9}; a, array name, is the address of the first int memory location. Access to a[5] returns an 2 3 -1 0 4 7 9 0 0 0 int value: 4. index 0 1 2 3 4 5 6 7 8 9 int b[3][5] = {{2, 3, -1, 0, 4}, {7, 9}, {6, 11, -2, 5}}; b, array name, is the address of the first int memory location. Access to b[2] returns the address of b[2][0] for the third row. 2 3 -1 0 4 7 9 0 0 0 6 11 -2 5 0 index [0][0] [0][1] [0][2] [0][3] [0][4] [1][0] [1][1] [1][2] [1][3] [1][4] [2][0] [2][1] [2][2] [2][3] [2][4] Access to b[0][2] returns an int value: -1. 10
  11. Introduction - Recall - Chapter 7 Pass a value of an element at index i of a one-dimension array a to functions Value passing - unchanged  Call to function func: func(a[i], ) Pass all the values of the elements of a one-dimension array a to functions Address passing - changeable  Call to function func: func(a, ) Pass a value of an element at indices i and j of a two-dimension array b to functions Value passing - unchanged  Call to function func: func(b[i][j], ) Pass a row at index i of a two-dimension array b to functions  Call to function func: func(b[i], ) Address passing - changeable Pass all the values of the elements of a two-dimension array b to functions Address passing - changeable  Call to function func: func(b, ) 11
  12. Introduction Related to physical memory addresses, pointers are provided as  A means for manipulation on memory  A means for pass-by-reference implementation  A means for dynamic data structures that can grow and shrink at execution time In Memory [1], Figure 7.1, pp. 254 12 In Memory In Memory
  13. Declare and initialize pointers A pointer of a data type  A variable whose value is an address of memory location that contains a value of a data type  Must be declared before its use optionally with an initial value type_name* variable_name =opt expressionopt; - variable_name: a valid identifier for a pointer - type_name: a valid data type (basic, derived, a new one with typedef) - type_name*: a pointer type for pointers that point to memory location of a data type type_name - expression: an initial value (0, NULL, an address) 13
  14. Declare and initialize pointers type_name* variable_name =opt expressionopt; // a variable of the char data type // an un-initialized pointer pointing to a char // a null pointer pointing to a char // a null pointer pointing to a char // a pointer pointing to a char with an initialized pointer to aChar pChar1 ??????? pChar2 000000 pChar3 000000 22FE37 pChar4 22FE37 aChar a 14
  15. Declare and initialize pointers type_name* variable_name =opt expressionopt; // a variable of the int data type // an un-initialized pointer pointing to an int // a null pointer pointing to an int // a null pointer pointing to an int // a pointer pointing to an int with an initialized pointer to anInt pInt1 ??????? pInt2 000000 pInt3 000000 22FE38 pInt4 22FE38 anInt 10 15
  16. Declare and initialize pointers type_name* variable_name =opt expressionopt; // a variable of the float data type // an un-initialized pointer pointing to a float // a null pointer pointing to a float // a null pointer pointing to a float // a pointer pointing to a float with an initialized pointer to aFloat pFloat1 ??????? pFloat2 000000 pFloat3 000000 22FE3C pFloat4 22FE3C aFloat 10.5 16
  17. Declare and initialize pointers type_name* variable_name =opt expressionopt; // a variable of the point3D data type // an un-initialized pointer pointing to a point3D // a null pointer pointing to a point3D // a null pointer pointing to a point3D // a pointer pointing to a point3D with an initialized pointer to aPoint pPoint1 ??????? pPoint2 000000 pPoint3 000000 22FE40 pPoint4 22FE40 aPoint 1.0 2.0 3.0 x y z 17
  18. Declare and initialize pointers 22FE37 ptrChar 22FE37 aChar a 22FE30 ptrInt 22FE30 9 ptrInteger 22FE30 anInt an int value in the memory an address of the memory location named anInt: 9 location named anInt: 22FE30 an address of the memory location an int value in the memory pointed by ptrInt: 22FE30 location pointed by ptrInt: 9 18
  19. Declare and initialize pointers A pointer of a data type  A variable whose value is an address of memory location that contains a value of a data type What if a particular data type is not told? Pointers to void void * pointer; 19
  20. Declare and initialize pointers Pointers to void  The generic pointer type which is a flexible means to manipulate memory for any data type Adaptive data structures Function definitions  A pointer to any data type can be assigned directly to a pointer of type void *.  A pointer of type void * can be assigned directly to a pointer to any data type.  A pointer of type void * can be casted to any data type.  A void * pointer cannot be dereferenced. 20
  21. Pointers to void Dereference of a void* pointer: *pVoid should be: *((int*)pVoid) 21
  22. Declare and initialize pointers A pointer of a data type  A variable whose value is an address of memory location that contains a value of a data type What if a data type is a pointer type? Pointers to pointers  A pointer that points to the memory location whose value is an address A conventional variable A pointer to an int memory location Pointers to pointers 22
  23. Pointers to pointers int pInt3; int pInt2; int* pInt1; int anInt; 22FE28 22FE30 pInt3 22FE30 22FE38 pInt2 22FE38 22FE44 pInt1 22FE44 anInt 10 pInt3 returns 10 pInt2 returns 10 *pInt1 returns 10 anInt returns 10
  24. Declare and initialize pointers const  A qualifier to inform the compiler that the value of a particular variable should not be modified  Recall – Constant variables in Chapter 3 INVALID! const short MAX = 50; Modification on constant variable: MAX = 55; A pointer of a data type  A variable whose value is an address of memory location that contains a value of a data type int* pInt; int anInt; How to apply const 22FE38 22FE44 pInt 22FE44 to a pointer? 24 anInt 10
  25. Declare and initialize pointers int* pInt; int anInt; How to apply const 22FE38 22FE44 to a pointer? pInt 22FE44 anInt 10 YES!!! Can it be constant? Can it be constant? Can it be constant? A non-constant pointer to non-constant data  As normal with no const qualifier A constant pointer to non-constant data A non-constant pointer to constant data A constant pointer to constant data 25
  26. Declare and initialize pointers int* pInt; int anInt; How to apply const 22FE38 22FE44 to a pointer? pInt 22FE44 anInt 10 constant non-constant non-constant? Read from right to left: pInt is a constant pointer to an int location. anInt += 5; //OK as modification is on a modifiable variable anInt *pInt = anInt + 5; //OK as modification is on a modifiable int location. pInt = &a[1]; //INVALID as modification is on a constant pointer. pInt3 = pInt; //OK as modification is on a modifiable pointer 26
  27. Declare and initialize pointers int* pInt; int anInt; How to apply const 22FE38 22FE44 to a pointer? pInt 22FE44 anInt 10 non-constant constant non-constant? Any modification on a constant location through a pointer is not allowed. Read from right to left: pInt is a pointer to a constant int location. anInt += 5; //OK as modification is on a modifiable variable anInt *pInt = anInt + 5; //INVALID as modification is on a constant int location. pInt = &a[1]; //OK as modification is on a modifiable pointer. pInt3 = pInt; //Warning: assignment discards 'const' qualifier from pointer target type
  28. Declare and initialize pointers int* pInt; int anInt; How to apply const 22FE38 22FE44 to a pointer? pInt 22FE44 anInt 10 constant constant constant? Any modification on a constant location through a pointer is not allowed. Read from right to left: pInt is a constant pointer to a constant int location. anInt += 5; //OK as modification is on a modifiable variable anInt *pInt = anInt + 5; //INVALID as modification is on a constant int location. pInt = &a[1]; //INVALID as modification is on a constant pointer. pInt3 = pInt; //Warning: assignment discards 'const' qualifier from pointer target type
  29. Operations on pointers int anInt = 10; anInt int* pInt = &anInt; pInt ? 10 ? ? ? Get an address of the memory location pointed by a pointer anInt pInt pInt ? 10 ? ? ? Get a value in the memory location pointed by a pointer anInt *pInt pInt ? 10 ? ? ? Get an address of the memory location next to the memory location pointed by a pointer anInt pInt+1 pInt+1 pInt ? 10 ? ? ? Get an address of the memory location before the memory location pointed by a pointer pInt-1 anInt pInt pInt-1 ? 10 ? ? ? 4 bytes 4 bytes 4 bytes
  30. Operations on pointers int anInt[5] = {1, 2, 3, 4, 5}; anInt int* pInt = anInt; pInt ? 1 2 3 4 5 Shift the pointer to the memory location next to the memory location currently pointed by the pointer anInt pInt++; pInt ? 1 2 3 4 5 ++pInt; Move the pointer back to the memory location before the memory location currently pointed by a pointer anInt pInt ; pInt ? 1 2 3 4 5 pInt; 30
  31. Operations on pointers i int i = 8; 8 int anInt[5] = {1, 2, 3, 4, 5}; anInt int* pInt = anInt; pInt ? 1 2 3 4 5 More assignments i 8 anInt pInt = &i; pInt ? 1 2 3 4 5 anInt pInt = &anInt[2]; pInt ? 1 2 3 4 5 anInt pInt += 2; pInt ? 1 2 3 4 5 31
  32. Operations on pointers i int i = 8; 8 int anInt[5] = {1, 2, 3, 4, 5}; anInt int* pInt = anInt; pInt ? 1 2 3 4 5 int* pInt2; //un-initialized!!! ? pInt2 ? More assignments anInt pInt ? 8 2 3 4 5 *pInt = i; ? INVALID! *pInt2 = anInt[2]; pInt2 3? i pInt2 = &i; VALID! pInt2 11 *pInt2 = *pInt + anInt[2]; 32
  33. Operations on pointers int anInt[5] = {1, 2, 3, 4, 5}; pInt3 int* pInt2 = anInt; anInt int* pInt3 = &anInt[2]; pInt2 ? 1 2 3 4 5 Comparisons pInt2 anInt results in: 0 (FALSE) pInt2 != NULL results in: 1 (TRUE) pInt2 != 2 results in: 1 (TRUE) //warning!!! pInt2 == 0 results in: 0 (FALSE) 33
  34. Pointers and arrays Arrays  A group of contiguous memory locations that all have the same type  Array name is the address of the first location among these contiguous memory locations. A constant pointer that points to the first element Pointers  A variable whose value is an address of memory location that contains a value of a data type Arrays and pointers are closely related and might be used interchangeably. 34
  35. Pointers and arrays int anInt[5] = {1, 2, 3, 4, 5}; anInt pInt ? 1 2 3 4 5 int* pInt = anInt; pInt: returns the address of the first element  pInt == &anInt[0] : TRUE *pInt or pInt[0]: returns the value of the first element  *pInt == pInt[0] == anInt[0] : TRUE pInt+i: returns the address of the (i+1)-th element  pInt+i == &anInt[i] : TRUE *(pInt+i) or pInt[i]: returns the value of the (i+1)-th element  *(pInt+i) == pInt[i] == anInt[i] : TRUE 35
  36. Pointers and arrays a pA ? 1 2 3 4 5 Equivalent access ways based on indices and addresses 36
  37. Pointers and arrays int anInt[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; int* pInt = anInt; anInt pInt ? 1 2 3 4 5 6 7 8 9 10 11 12 row 0 row 1 row 2 pInt: returns the address of the first element at row 0 and column 0  pInt == &anInt[0][0] : TRUE *pInt: returns the value of the first element at row 0 and column 0  *pInt == anInt[0][0] : TRUE 37
  38. Pointers and arrays int anInt[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; int* pInt = anInt; anInt pInt ? 1 2 3 4 5 6 7 8 9 10 11 12 row 0 row 1 row 2 pInt + column_size*i + j: returns the address of the element at row i and column j  pInt + column_size*i + j == &anInt[i][j] : TRUE *(pInt + column_size*i + j): returns the value of the element at row i and column j  *(pInt + column_size*i + j) == anInt[i][j] : TRUE pInt + 4*1 + 1 = pInt + 5: returns &anInt[1][1] pInt + 4*2 + 1 = pInt + 9: returns &anInt[2][1] *(pInt+5): returns anInt[1][1], i.e. 6 *(pInt+9): returns anInt[2][1], i.e. 10 38
  39. Pointers and arrays int anInt[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; int pInt; What happens with a pointer to pointer for a multidimensional array? pInt pInt[0] pInt[1] anInt pInt[2] 1 2 3 4 5 6 7 8 9 10 11 12 row 0 row 1 row 2 int int* int NOTE: pInt[0]: returns anInt[0]; - anInt is a constant pointer that points to the first element pInt[1]: returns anInt[1]; anInt[0][0]. pInt[2]: returns anInt[2]; - pInt is a pointer that points to pointer pInt[0]. pInt[i][j]: returns anInt[i][j] 39
  40. Variable storage and heap memory - Recall – Chapter 3 Memory layout of a C program Higher address Command-line arguments and environment variables Local variables, arguments, Stack grown/shrunk with function calls Grown/shrunk with dynamic allocation and de-allocation Heap Uninitialized (static) global Uninitialized data Initialized to variables, static local variables .bss zero by exec Initialized (static) global variables, Initialized data Read from static local variables, constants .data program file Machine code, often read-only Code by exec .text Lower address bss = block started by symbol, better save space
  41. Variable storage and heap memory Memory layout of a C program Higher address Command-line arguments and environment variables Local variables, arguments, Stack grown/shrunk with function calls pointer Grown/shrunk with dynamic allocation and de-allocation Heap Uninitialized (static) global Uninitialized data Initialized to variables, static local variables .bss zero by exec Initialized (static) global variables, Initialized data Read from static local variables, constants .data program file Machine code, often read-only Code by exec .text Lower address bss = block started by symbol, better save space
  42. Memory allocation and de-allocation Dynamically allocated arrays  Located in heap memory  Handled by means of pointers  Unknown size at compile time  Dynamically grown/shrunk at execution time  Allocated/de-allocated explicitly by programmers Standard library Allocation: malloc, calloc, realloc PAIRED!!! De-allocation: free 42
  43. Memory allocation and de-allocation Allocation  void* malloc(size_t size) Allocates the requested memory and returns a pointer to it  void* calloc(size_t nitems, size_t size) Allocates the requested memory and returns a pointer to it  void* realloc(void* ptr, size_t size) 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
  44. Define an array of 5 integer numbers in heap memory Allocation Check if OK Allocation Check if OK USE De-Allocation De-Allocation 44
  45. 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
  46. 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
  47. 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
  48. 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
  49. 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
  50. 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
  51. 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
  52. 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
  53. 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
  54. 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
  55. 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
  56. 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
  57. 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
  58. 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
  59. 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
  60. 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
  61. 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
  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; 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
  63. 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
  64. 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
  65. 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
  66. 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
  67. Given n locations, find the nearest locations from your current location. 67
  68. 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
  69. 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
  70. Pass pointers to a function Swap a and b: Address passing via variables‟ addresses Address passing via pointers that point to the variables 70
  71. 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
  72. 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
  73. 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
  74. 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
  75. Function for matrix multiplication: res = m1xm2 75
  76. Function for generating a matrix m with size rxc 76
  77. Functions for inputting a natural number and printing a matrix 77
  78. 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
  79. 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
  80. 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
  81. 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
  82. 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
  83. 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
  84. 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
  85. 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
  86. Chapter 8: Pointers 86