Unit 6Week 10 & 11   Pointers     andDynamic Arrays
Unit Objectives   Introducing Pointers       Pointer Variables       Basic Memory Management       Static, Dynamic, an...
6.1 Pointers    Pointers are symbolic representation of    addresses. Pointers enable programs to    simulate call-by-ref...
6.1.1 Pointer Variable    Declaration and Initialization   Pointer variables contain memory addresses    as their values....
6.1.1 (Cont..) Pointer are declared same as variable before  you can use them as follows:     int ∗xptr, ∗yptr, count;De...
6.1.2 Pointer Operations   The & or address operator, is a unary operator that returns    the address of its operand.   ...
6.1.2 (Cont..)The statement z = *yptr //will return to content of where yptr “point to” z = 5   The ∗ operator referred t...
6.1.2 (Cont..)   Consider the following memory locations    int y =5;               int *yptr;             5             ...
6.1.2 (Cont..)Note: You must assign an address to a pointer.  Dereferencing a pointer that has not been properly  initial...
Example// showing pointer application#include <iostream>using namespace std;int main ( ){   int a;   int *aptr;    // aptr...
Example (Cont..)aptr = &a; // aptr set to address to a  cout << ”The address of a is” << &a    << ”n The value of aptr is”...
Example (Cont..)The output of the above program is:The address of a is 0X0064FDF4The value of aptr is 0X0064FDF4The value ...
6.1.3 References and Pointers   There are 3 ways in C++ to pass arguments to a    function2.  call-by-value3.  call-by-re...
6.1.3 (Cont..)   References do not require the indirection operator    to locate the final value being accessed, whereas ...
Example// Find a cube of a variable with a pointer argument#include <iostream>using namespace std;void cube (int *); // pr...
Example (Cont..)cout << ”n The new value of number is “<< number   <<endl;return 0;}void cube ( int *nptr){ *nptr =(*nptr)...
6.2 Array Name as Pointers An array name is a pointer constant. The value of the pointer constant is the  address of the...
Example// pointer to arrays#include <iostream>using namespace std;void printarray ( int*, int)int main ( ){   const int ar...
Example (Cont..)printarray (grade, arraysize);  for ( int i = 0; i < 5; i++)  cout << ”n Element “<< i <<” is “ << *ptr+  ...
Example (Cont..)void printarray ( int *ptrgrade, int MAX){  int constant = 10;for (int i = 0; i < MAX; i++)  *ptrgrade++ +...
Example (Cont..)The output of the above program is:Element 0 is 103Element 1 is 98Element 2 is 104Element 3 is 101Element ...
Example// Example of pointers and strings and const data#include <iostream>using namespace std;void printc (const char * )...
Example (Cont..)printc (string);cout << endl;return 0;}void printc (const char *sptr){                        // sptr is “...
6.2 (Cont..)   If a value does not ( or should not) change    in the body of a function to which it is    passed, the par...
Example// converting lowercase letter to uppercase letters// using non-constant pointer#include <iostream>#include <ctype>...
Example (Cont..)char string [ ] = “characters and $32.98”;cout << ”the string before conversion is: ” << string;convert (s...
Example (Cont..){while (*sptr !=’0’)  {    if ( *sptr >= ’a’ && *sptr <= ’z’)*sptr = toupper ( *sptr); // convert to upper...
Example (Cont..)The output of the above program is:the string before conversion is: characters and  $ 32.98the string afte...
6.3 Pointer Expressions and    Pointer Arithmetic   A limited set of arithmetic operations may    be performed on pointer...
6.3 (Cont..)   Assume that array int arr [5] has been    declared and its first element is at location    100 in memory. ...
6.3 (Cont..)For example, the statement  ptrarr +=2      =100+2*2=104  ptrarr -=1      =104-2*1=102  ++ptrarr = 104 Finall...
6.3 (Cont..)  Pointer arithmetic is meaningless unless performed   on an array.// using strcpy and strncpy#include <iostr...
Example (Cont..)  << ”n The string in array y is: “ << strcpy(y, x)   << ”n”;strncpy (z, x, 14); // does not copy null cha...
Example (Cont..)The output of the above program is:The string in array x is: Happy Birthday to youThe string in array y is...
6.3 (Cont..)   Functions strcpy ( ) copies its second    argument (a string) into its first argument    which must be lar...
6.3 (Cont..)   strncpy ( ) is equivalent to strcpy ( ) except    that strncpy ( ) specifies the number of    characters t...
Example// using strcat and strncat#include <iostream>#include <string>using namespace std;int main ( ){char s1[20 ]=”Happy...
Example (Cont..)cout << ”s1= “ << s1 << ”n s2 = “ << s2;cout << ”n strcat ( s1, s2) = “ << strcat (s1, s2);cout << ”n strn...
Example (Cont..)The output of the above program is:s1 = Happys2 = New Yearstrcat (s1, s2) = Happy New Yearstrncat (s3, s1,...
6.3 (Cont..)   Function strncat ( ) appends a specified number of    characters from the second string to the first strin...
Example// using strcmp and strncmp#include <iostream>#include <string>using namespace std;int main ( ){   char *s1 = “Happ...
Example (Cont..)cout << ”strcmp(s1, s2) = “ << strcmp (s1, s2)   << "n strcmp (s1, s3) = " << strcmp (s1, s3)   << ”n strc...
Example (Cont..)return 0;}The output of the above program is:strcmp (s1, s2) = 0strcmp (s1, s3) = 1strcmp (s3, s1) = -1str...
6.4 Advanced Pointer Notation Here first, we consider pointer notation for  the two-dimensional numeric arrays.  consider...
6.4 (Cont..)More specificallyPointer Notation   Array Notation      Value  *(*nums)          nums[ 0 ] [ 0 ]    16  *(*num...
ExampleWrite a program that initialize three two-dimensional   array of your choice and then call a user-defined   functio...
Example (Cont..)int a [2] [3] = {{1,2,3},{5,3,2}};int b [2] [3] = {{1,3,5},{2,0,8}};static int c [ 2 ] [ 3 ];addarray ( a,...
Example (Cont..)for ( int j= 0; j< 3; j++)  cout << *(*(c+i) +j) << setw(3);  cout << endl;  cout << ”nn”;}return 0;}
Example (Cont..)void addarray ( int (*pta)[ 3 ], int *(ptb)[ 3 ],  int *(ptc)[ 3 ]){  for (int i =0; i<2; i++)   for(int j...
6.5 Pointer Arrays   The declaration of an array of character    pointer is an extremely useful extension to    single st...
6.5 (Cont..)   As individual pointers, each pointer can be    assigned to point to a string using string    assignment st...
6.5.1 Initializing arrays of    pointers to strings  The initialization of the seasons array can  also be incorporated di...
Example// string and pointer example#include < iostream>using namespace std;int main ( ){int n;char *seasons [ ] = { “Wint...
Example (Cont..)cin >> n;n = (n % 12) / 3; // create the correct subscriptcout << ”The month entered is a << seasons [ n ]...
Example (Cont..)The output of the above program is:Enter a month ( use 1 for Jan 2 for Feb, etc.) : 12The month entered is...
ExampleThe following example is the modification to   previous example in this case a function is used to   print seasons....
Example (Cont..)cout << ”n Enter a month ( use 1 for Jan, etc.) : “;cin >> n;st_pt (seasons, n);return 0;}void st_pt (char...
Example (Cont..)n = (n%12)/3;cout << ”The month entered is a “ << *(ys +  n)  <<” month.” <<endl;}
6.5.1 (Cont..)   Pointers are exceptionally useful in    constructing string-handling functions when    pointer notation ...
Upcoming SlideShare
Loading in...5
×

Unit 6 pointers

4,030

Published on

Intro to C++ Powerpoint on Pointers.

Published in: Education, Technology, Business
0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
4,030
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
284
Comments
0
Likes
3
Embeds 0
No embeds

No notes for slide

Unit 6 pointers

  1. 1. Unit 6Week 10 & 11 Pointers andDynamic Arrays
  2. 2. Unit Objectives Introducing Pointers  Pointer Variables  Basic Memory Management  Static, Dynamic, and Automatic Variables  Pointer Arithmetic Dynamic Arrays  Array Variables and Pointer Variables
  3. 3. 6.1 Pointers Pointers are symbolic representation of addresses. Pointers enable programs to simulate call-by-reference and to create and manipulate dynamic data structures.
  4. 4. 6.1.1 Pointer Variable Declaration and Initialization Pointer variables contain memory addresses as their values. A variable directly references a value, and a pointer indirectly references a value. Referencing a value through a pointer is called indirection. The ∗ is called indirection operator.
  5. 5. 6.1.1 (Cont..) Pointer are declared same as variable before you can use them as follows: int ∗xptr, ∗yptr, count;Declares the variable xptr, a pointer to an integer value or double ∗dptr;Declares the variable dptr, a pointer to a double value.
  6. 6. 6.1.2 Pointer Operations The & or address operator, is a unary operator that returns the address of its operand. For example, int y =5; int *xptr, *yptr, Z; and statement yptr = &y; assigns the address of the variable y to pointer variable yptr. Variable yptr is then said to “point to” y.
  7. 7. 6.1.2 (Cont..)The statement z = *yptr //will return to content of where yptr “point to” z = 5 The ∗ operator referred to a dereferencing operator which returns the content where a pointer variable “points to”.
  8. 8. 6.1.2 (Cont..) Consider the following memory locations int y =5; int *yptr; 5 100 100 120 y yptr 102 122 104 124 106
  9. 9. 6.1.2 (Cont..)Note: You must assign an address to a pointer. Dereferencing a pointer that has not been properly initialized, could cause a fatal execution time error, or it could cause accidentally modify important data and allow the program to run to completion providing incorrect results. An attempt to dereference a non-pointer is a syntax error.
  10. 10. Example// showing pointer application#include <iostream>using namespace std;int main ( ){ int a; int *aptr; // aptr is a pointer to an integer a = 7;
  11. 11. Example (Cont..)aptr = &a; // aptr set to address to a cout << ”The address of a is” << &a << ”n The value of aptr is” << aptr; cout << ”n The value of a is” << a << “n The value of *aptr is << *aptr << endl;return 0;}
  12. 12. Example (Cont..)The output of the above program is:The address of a is 0X0064FDF4The value of aptr is 0X0064FDF4The value of a is 7The value of *aptr is 7
  13. 13. 6.1.3 References and Pointers There are 3 ways in C++ to pass arguments to a function2. call-by-value3. call-by-reference with reference argument4. call-by-reference with pointer argumentThe differences between the last two are: The address named as a reference can not be altered. But because pointer is a variable, the address in the pointer can be changed.
  14. 14. 6.1.3 (Cont..) References do not require the indirection operator to locate the final value being accessed, whereas pointers do. References are automatically or implicitly dereferenced, whereas pointers must be explicitly dereferenced. References provide a simpler notational interface and are usually preferred. Pointers are used for dynamically allocating new sections of memory for additional variables as a program is running or using alternative to array notation.
  15. 15. Example// Find a cube of a variable with a pointer argument#include <iostream>using namespace std;void cube (int *); // prototypeint main ( ){int number = 5;cout << ”The original value of number is” << number << endl;cube (&number);
  16. 16. Example (Cont..)cout << ”n The new value of number is “<< number <<endl;return 0;}void cube ( int *nptr){ *nptr =(*nptr)*(*nptr)*(*nptr); }note that there is no return from function cube to main ( )
  17. 17. 6.2 Array Name as Pointers An array name is a pointer constant. The value of the pointer constant is the address of the first element. Thus, if val is the name of an array, val and &val [ 0 ] can be used interchangeably.Creating an array also creates a pointerint grade [ 2 ] grade [ 0 ] grade [ 1 ] *grade *(grade + 1)
  18. 18. Example// pointer to arrays#include <iostream>using namespace std;void printarray ( int*, int)int main ( ){ const int arraysize = 5; int grade [arraysize] = { 93, 88, 94, 91, 82}; int *ptr; ptr = grade; // or ptr=&grade [ 0 ];
  19. 19. Example (Cont..)printarray (grade, arraysize); for ( int i = 0; i < 5; i++) cout << ”n Element “<< i <<” is “ << *ptr+ +; // or *(grade+i) cout << endl; return 0; }
  20. 20. Example (Cont..)void printarray ( int *ptrgrade, int MAX){ int constant = 10;for (int i = 0; i < MAX; i++) *ptrgrade++ += constant;}
  21. 21. Example (Cont..)The output of the above program is:Element 0 is 103Element 1 is 98Element 2 is 104Element 3 is 101Element 4 is 92
  22. 22. Example// Example of pointers and strings and const data#include <iostream>using namespace std;void printc (const char * );int main ( ){char string [ ] = “print characters of a string”;cout << ”The string is: n”;
  23. 23. Example (Cont..)printc (string);cout << endl;return 0;}void printc (const char *sptr){ // sptr is “read-only” pointerfor ( ; *sptr !=’0’; sptr ++) // no initialization cout << *sptr;}
  24. 24. 6.2 (Cont..) If a value does not ( or should not) change in the body of a function to which it is passed, the parameter should be declared const to ensure that it is not accidentally modified.
  25. 25. Example// converting lowercase letter to uppercase letters// using non-constant pointer#include <iostream>#include <ctype>using namespace std;void convert ( char *);int main ( ){
  26. 26. Example (Cont..)char string [ ] = “characters and $32.98”;cout << ”the string before conversion is: ” << string;convert (string);cout << ”n the string after conversion is: “ << string << endl;return 0;}void convert ( char *sptr)
  27. 27. Example (Cont..){while (*sptr !=’0’) { if ( *sptr >= ’a’ && *sptr <= ’z’)*sptr = toupper ( *sptr); // convert to uppercase ++sptr; // move sptr address to the next character }}
  28. 28. Example (Cont..)The output of the above program is:the string before conversion is: characters and $ 32.98the string after conversion is: CHARACTERS AND $ 32.98
  29. 29. 6.3 Pointer Expressions and Pointer Arithmetic A limited set of arithmetic operations may be performed on pointers. A pointer may be  incremented ( ++ )  decremented ( -- )  an integer may be added to a pointer ( + or - )  an integer may be subtracted from a pointer ( - or -= )
  30. 30. 6.3 (Cont..) Assume that array int arr [5] has been declared and its first element is at location 100 in memory. Assume pointer int *ptrarr has been initialized to the beginning address of arr, i.e.; 100. 100 102 104 106 108
  31. 31. 6.3 (Cont..)For example, the statement ptrarr +=2 =100+2*2=104 ptrarr -=1 =104-2*1=102 ++ptrarr = 104 Finally, pointer variables may be subtracted from another. For example, if ptrarr 2 = 100 and ptrarr1 = 102 then x = ptrarr2 –ptrarr1=2
  32. 32. 6.3 (Cont..) Pointer arithmetic is meaningless unless performed on an array.// using strcpy and strncpy#include <iostream>#include <string>using namespace std;int main ( ){ char x [ ] = “Happy Birthday to you”; char y [ 25 ], z [15 ]; cout << ”The string in array x is:”<< x
  33. 33. Example (Cont..) << ”n The string in array y is: “ << strcpy(y, x) << ”n”;strncpy (z, x, 14); // does not copy null characterz [14] = ‘0’;cout << ”The string in array z is: “ << z << endl;return 0;}
  34. 34. Example (Cont..)The output of the above program is:The string in array x is: Happy Birthday to youThe string in array y is: Happy Birthday to youThe string in array z is: Happy Birthday
  35. 35. 6.3 (Cont..) Functions strcpy ( ) copies its second argument (a string) into its first argument which must be large enough to store the string and the terminating null character.
  36. 36. 6.3 (Cont..) strncpy ( ) is equivalent to strcpy ( ) except that strncpy ( ) specifies the number of characters to be copied from the string into the array. Note that the function strncpy ( ) does not necessarily copy the terminating null character of its second argument – a terminating null character is written only if the number of characters to be copied is at least one more than the length of the string.
  37. 37. Example// using strcat and strncat#include <iostream>#include <string>using namespace std;int main ( ){char s1[20 ]=”Happy ”;char s2 [ ] = “New Year”;char s3 [40] = “ “;
  38. 38. Example (Cont..)cout << ”s1= “ << s1 << ”n s2 = “ << s2;cout << ”n strcat ( s1, s2) = “ << strcat (s1, s2);cout << ”n strncat (s3, s1, 6) = “<< strncat (s3, s1, 6);cout << ”n strcat (s3, s1,) = ” << strcat(s3, s1) << endl;return 0;}
  39. 39. Example (Cont..)The output of the above program is:s1 = Happys2 = New Yearstrcat (s1, s2) = Happy New Yearstrncat (s3, s1, 6) = Happystrcat (s3, s1) = Happy Happy New Year
  40. 40. 6.3 (Cont..) Function strncat ( ) appends a specified number of characters from the second string to the first string. A terminating null character is appended to the result. Assuming that strcmp ( ) and strncmp ( ) return 1 when their argument are equal is a logic error. Both functions return 0 ( C++’s false value ) for equality. Therefore, when testing two strings for equality, the result of the strcmp ( ) or strncmp ( ) function should be compared with 0 to determine if the strings are equal.
  41. 41. Example// using strcmp and strncmp#include <iostream>#include <string>using namespace std;int main ( ){ char *s1 = “Happy New Year”; char *s2 = “Happy New Year”; char *s3 = “Happy Holidays”;
  42. 42. Example (Cont..)cout << ”strcmp(s1, s2) = “ << strcmp (s1, s2) << "n strcmp (s1, s3) = " << strcmp (s1, s3) << ”n strcmp (s3, s1) = “ << strcmp (s3, s1); cout << ”nn strncmp (s1, s3, 6) = “ << strncmp (s1, s3, 6) << ”n strncmp (s1, s3, 7 ) = “ << strncmp (s1,s3, 7) << ”n strncmp (s3, s1, 7) = “ << strncmp (s3, s1, 7)<<endl;
  43. 43. Example (Cont..)return 0;}The output of the above program is:strcmp (s1, s2) = 0strcmp (s1, s3) = 1strcmp (s3, s1) = -1strncmp (s1, s3, 6) = 0strncmp (s1, s3, 7) =1strncmp (s3, s1, 7) =1
  44. 44. 6.4 Advanced Pointer Notation Here first, we consider pointer notation for the two-dimensional numeric arrays. consider the following declarationint nums[2][3] = {{16,18,20},{25,26,27}}; In general,nums[ i ][ j ] is equivalent to *(*(nums+i)+j)
  45. 45. 6.4 (Cont..)More specificallyPointer Notation Array Notation Value *(*nums) nums[ 0 ] [ 0 ] 16 *(*nums + 1) nums [ 0 ] [ 1 ] 18 *(*nums + 2) nums [ 0 ] [ 2 ] 20 *(*(nums + 1)) nums [ 1 ] [ 0 ] 25 *(*(nums + 1) +1) nums [ 1 ] [ 1 ] 26 *(*(nums + 1) +2) nums [ 1 ] [ 2 ] 27
  46. 46. ExampleWrite a program that initialize three two-dimensional array of your choice and then call a user-defined function to add these two arrays and print the result in the main ( ).#include <iostream>#include <iomanip>using namespace std;void addarray (int(*pta)[3],int(*ptb)[3],int(*ptc)[3]);int main ( ){
  47. 47. Example (Cont..)int a [2] [3] = {{1,2,3},{5,3,2}};int b [2] [3] = {{1,3,5},{2,0,8}};static int c [ 2 ] [ 3 ];addarray ( a, b, c); for (int i=0; i < 2; i++){
  48. 48. Example (Cont..)for ( int j= 0; j< 3; j++) cout << *(*(c+i) +j) << setw(3); cout << endl; cout << ”nn”;}return 0;}
  49. 49. Example (Cont..)void addarray ( int (*pta)[ 3 ], int *(ptb)[ 3 ], int *(ptc)[ 3 ]){ for (int i =0; i<2; i++) for(int j=0; j<3; j++) *(*(ptc + i)+j) = *(*(pta + i)+j) + *(*(ptb + i)+j);}
  50. 50. 6.5 Pointer Arrays The declaration of an array of character pointer is an extremely useful extension to single string declaration. For example, the declarations char *seasons [ 4 ]; create an array of four elements, where each element is a pointer to a character.
  51. 51. 6.5 (Cont..) As individual pointers, each pointer can be assigned to point to a string using string assignment statements. Thus, the statements seasons [ 0 ] = “Winter”; seasons [ 1 ] = “Spring”; seasons [ 2 ] = “Summer”; seasons [ 3 ] = “Fall”; // sting lengths may differ
  52. 52. 6.5.1 Initializing arrays of pointers to strings The initialization of the seasons array can also be incorporated directly within the definition of the array as follows:char *seasons [ 4 ] = {“Winter”, “Spring”, “Summer”, “Fall”};
  53. 53. Example// string and pointer example#include < iostream>using namespace std;int main ( ){int n;char *seasons [ ] = { “Winter”, “Spring”, “Summer”, “Fall”};cout << ”n Enter a month (use 1 for Jan, 2 for Feb, etc):”;
  54. 54. Example (Cont..)cin >> n;n = (n % 12) / 3; // create the correct subscriptcout << ”The month entered is a << seasons [ n ] // or * (seasons + n) << ”month” << endl;return 0;}
  55. 55. Example (Cont..)The output of the above program is:Enter a month ( use 1 for Jan 2 for Feb, etc.) : 12The month entered is a Winter month
  56. 56. ExampleThe following example is the modification to previous example in this case a function is used to print seasons. #include <iostream>using namespace std;void st_pt ( char *ys [ ], int n);int main ( ){ int n; char *seasons [ ] = { “Winter”, “Spring”, “Summer”, “Fall”};
  57. 57. Example (Cont..)cout << ”n Enter a month ( use 1 for Jan, etc.) : “;cin >> n;st_pt (seasons, n);return 0;}void st_pt (char *ys [ ], int n){
  58. 58. Example (Cont..)n = (n%12)/3;cout << ”The month entered is a “ << *(ys + n) <<” month.” <<endl;}
  59. 59. 6.5.1 (Cont..) Pointers are exceptionally useful in constructing string-handling functions when pointer notation is used in place of subscripts to access individual characters in a string, the resulting statements are both more compact and more efficient.
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×