Pointers by wanghonghx

VIEWS: 8 PAGES: 20

									        CS110: Lecture 15
            Pointers:
      ‘Movable Array Names’
                 Jack Tumblin
            jet@cs.northwestern.edu


I hope you:
  – Are reading Chapter 9.
  – Have read Chapter 11-1,2,5
                Parsing (not in book)
• Jargon: ‘parse’ == extract/decode meaning
      – split a string into words (Jargon: ‗tokens‘)
      – look up each token in a computerized ‗dictionary‘, etc....


 How can we parse this phrase?
         char msg[81] = {“nasty, brutish, and short”};

msg
                             address  

 n a s t y ,                b r u t i s h ,.                  a n d.        s h o r t         \0


 (from Leviathan,--Thomas Hobbes, 1651: ―No arts; no letters; no society, and which is worst of all,
              continual fear and danger of violent death; and the life of man, solitary, poor,
              nasty, brutish, and short.‖ 150 years later, it was a British joke told about Napoleon)
              Parsing (not in book)
• Jargon: ‘parse’ == extract/decode meaning
      – split a string into words (Jargon: ‗tokens‘)
      – look up each token in a computerized ‗dictionary‘, etc. ...


• IDEA! write \0 at spaces to make one-token strings:
         char msg[81]= {“nasty, brutish, and short”};

msg
                        address  

 n a s t y ,       \0   b r u t i s h ,.\0 a n d.\0 s h o r t         \0
           Parsing (not in book)
• But now, how do we read/print/use those words?

• BEST: split msg array into several smaller arrays.
   – BUT WE CAN’T: arrays are fixed size, fixed location.
   – ?must we copy perfectly good strings to other arrays?!?!
     wasteful! slow! inflexible! complicated! Surely you jest!

       char msg[81]= {“nasty, brutish, and short”};
msg
                     address  

  n a s t y ,   \0   b r u t i s h ,.\0 a n d.\0 s h o r t       \0


 pW0              pW1                    pW2       pW3
            The Answer: Pointers
 • (Recall) array name (msg) holds the
              memory address of the 0th byte of array.
 • But the address of an array is fixed, a constant;
   we want a ‘movable array name’ (w0,w1,…) that
      – has an adjustable/variable address,
      – does not make any new array elements
       char msg[81]= {“nasty, brutish, and short”};
msg
                     address  

 n a s t y ,    \0   b r u t i s h ,.\0 a n d.\0 s h o r t   \0


pW0               pW1                  pW2     pW3
         A new kind of Variable:
                Pointers
• (Recall) Variable: a named chunk of memory, a
   placeholder for one stored value that can change.

• (Recall) Array: a named chunk of memory, a
  placeholder for many stored values that can change.
   – Array name (e.g. msg) gives fixed address; tells byte 0 of the array
   – Array elements (e.g. msg[3]) are measured from there


• (NEW!)
  Pointer: a named chunk of memory,
  a placeholder for one address in memory.
            The Answer: Pointers
 • (Recall) array name (msg) holds the
              memory address of the 0th byte of array.
 • But the address of an array is fixed, a constant;
   we want a ‘movable array name’ (w0,w1,…) that
      – has an adjustable/variable address,
      – does not make any new array elements A variable that
                                             stores an address!
msg
                     address  
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
 n a s t y ,    \0   b r u t i s h ,.\0 a n d.\0 s h o r t   \0


pW0=68;           pW1=75;              pW2=84;    pW3=88;
              Declaring Pointers
      • Pointers: a variable that holds an address
      • Must declare a pointer and initialize it before use.
           base-type * var_name; (* is crucial!)
      Examples:
      char *pW0, *pW1, *pW2, *pW3;       /* pointers to words */




msg
                       address  
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
 n a s t y ,      \0   b r u t i s h ,.\0 a n d.\0 s h o r t   \0


      pW1          pW3
pW0         pW2
        Declaring pointers
• Why do we need the asterisk?

  – Because ‗*‘ tells compiler:
    ‘this variable holds an ADDRESS, not a value’
  – Pointer-to-int is VERY different from int!
          Declaring pointers
• The asterisk goes with the name, not the
  type:
   int *pcount; /* a pointer to int, named pcount */


   int *pcount, *pnum; /* two pointers to int, named
                        pcount and pnum */


   int *pcount, number; /* a pointer to int named pcount
                        and an int named number */
             Setting Pointer Values
• Must declare a pointer and then initialize it before use.
• But C hides memory addresses from us!
  ?? How can we get an address value to put in a pointer?
      – 1) From array names (they hold address of 0th byte in array)

        char *pW0, *pW1, *pW2, *pW3;

        pW0 = msg;     /* pW0 points to array „msg‟ */
msg
                     address  
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
  n a s t y , \0 b r u t i s h ,.\0 a n d          \0   s h o r t   \0

        pW1 pW3
pW0
               pW2
              Setting Pointer Values
 • But C hides memory addresses from us!
   ?How can we get an address value to put in a pointer?
      – 1) From array names (they hold address of 1st byte in array)
      – 2) From other pointers of the same type, or…

        char *pW0, *pW1, *pW2, *pW3;

        pW0 = msg;   /* pW0 points to array „msg‟ */
msg     pW1 = pW2 = pW0;
                        address  
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
  n a s t y , \0 b r u t i s h ,.\0 a n d         \0   s h o r t   \0

                  pW2
pW0         pW3
      pW1
             Setting Pointer Values
• But C hides memory addresses from us!
  ?How can we get an address value to put in a pointer?
      – 1) From array names (they hold address of 1st byte in array)
      – 2) From other pointers of the same type,
      – 3) Address math with pointer values; addresses are ints
       char *pW0, *pW1, *pW2, *pW3;     char *pW0, *pW1, *pW2, *pW3;

           pW0   =   msg;                   pW0   =   msg;
           pW1   =   msg +   7;             pW1   =   pW0 + strlen(pW0) +1;
           pW2   =   pW1 +   9;             pW2   =   pW1 + strlen(pW1) +1;
           pW3   =   pW2 +   4;             pW3   =   pW2 + strlen(pW2) +1;
msg
                         address  

 n a s t y , \0 b r u t i s h ,.\0 a n d               \0   s h o r t   \0


pW0                    pW1                 pW2              pW3
                Setting Pointer Values
How to get an address value to put in a pointer:
      – 1) From array names (they hold address of 1st byte in array)
      – 2) From other pointers of the same type,
      – 3) Address math with pointer values; addresses are ints
How to use pointers: as (movable) array names
char *pW0,*pW1,*pW2, *pW3;         printf(“%s %s %s %s”,pW3,pW2,pW1,pW0);

      pW0   =   msg;               RESULT:
      pW1   =   msg + 7;           > short and brutish, nasty,
      pW2   =   pW1 + 9;           >
      pW3   =   pW2 + 4;

msg
                           address  

 n a s t y , \0 b r u t i s h ,.\0 a n d             \0   s h o r t   \0


pW0                    pW1                   pW2          pW3
                Setting Pointer Values
How to use pointers: as (movable) array names
• Array index []works for pointers!
char *pW0,*pW1,*pW2, *pW3;           printf(“%s %s %s %s”,pW0,pW1,pW2,pW3);
                                     pW0[0] = „T‟;
      pW0   =   msg;                 pW1[2] = „i‟;
      pW1   =   msg +   7;           pW2[0] = „e‟;
      pW2   =   pW1 +   9;           pW3[1] = „n‟;
      pW3   =   pW2 +   4;           printf(“%s %s %s %s”,pW0,pW1,pW2,pW3);
                                     RESULT:
                                     > nasty, brutish, and short
                                     > Tasty, british, end snort
msg
                             address  

 T a s t y , \0 b r i t i s h ,.\0 e n d                \0   s n o r t   \0


pW0                      pW1                    pW2          pW3
                Setting Pointer Values
How to use pointers: as (movable) array names
• Array index []works for pointers!
• Move ‗array names‘ by ordinary integer math! Example:
                                    printf(“%s %s %s %s”,pW3,pW2,pW1,pW0);
char *pW0,*pW1,*pW2,*pW3;
                                    pW0 += 2;
                                    pW1 = pW1 +4;
      pW0   =   msg;
                                    pW2 = pW3 +3;
      pW1   =   msg + 7;
                                    pW3 = pW3 -2;
      pW2   =   pW1 + 9;
                                    printf(“%s %s %s %s”,pW3,pW2,pW1,pW0);
      pW3   =   pW2 + 4;
                                   RESULT:
                                   > nasty, brutish, and short
                                   > sty, ish, rt d
msg
                   address  

 n a s t y , \0 b r u t i s h ,.\0 a n d             \0   s h o r t   \0


pW0 pW0                pW1        pW1        pW2 pW3 pW3       pW2
                    Using Pointers
• As ‘movable array names’: array index []works!
• As ‘movable array names’:do address math using ints
       int i=0;
       char ch;

           while((pW0[i] != ‟\0‟) && (pW1[i] != ‟\0‟))
           {     /* while both chars are not NULL */
               ch = pW0[i];     /* swap characters */
               pW0[i] = pW1[i];
               pW1[i] = ch;
               i++;         /* go on to next char */
           }
                                                      Result:
           printf(“%s %s\n”,pW0,pW1);
msg                                                  > brutis, nasty,h,
                                                     >

  n a s t y , \0 b r u t i s h ,.\0 a n d.\0 s h o r t          \0


 pW0               pW1                    pW2       pW3
                     Using Pointers
• As ‘movable array names’: array index []works!
• As ‘movable array names’:do address math using ints
       char ch;

           while((pW0[0] != ‟\0‟) && (pW1[0] != ‟\0‟))
           {     /* while both chars are not NULL */
               ch = pW0[0];     /* swap characters */
               pW0[0] = pW1[0];
               pW1[0] = ch;
               pW0++;       /* go on to next char */
                                                       Result:
               pW1++;
           }                                           > brutis,   nasty,h,
           printf(“%s %s\n”,pW0,pW1);                  >
msg

  n a s t y , \0 b r u t i s h ,.\0 a n d.\0 s h o r t              \0


 pW0                pW1                    pW2       pW3
       Using Pointers for Strings
• move them around—do address math using ints
• Use them as ‘movable array names’: array index []works!
• Pointers can define a string just as an array does:
  int i=0;
  printf(“array msg holds string----:%s \n”,msg);
  printf(“string at pointer pW0 is---:%s \n”,pW0);
  printf(“string at pointer pW1 +3 is:%s \n”,pW1+3);
        Result:
        > array msg holds string----:brutis
        > string at pointer pW0 is---:brutis
msg     > string at pointer pW1 +3 is:ty,h,


  b r u t i s   /0   n a s t y , h ,./0 a n d./0 s h o r t   /0


 pW0              pW1     pW1+3        pW2     pW3
                  Pointers So Far:
• Pointer: a new kind of variable that holds an address
                         instead of a number or char
• Must declare and initialize before use: char *pW0;
  (hint: use ‘p’ prefix for pointer names)             pW0 = msg;
• Pointers behave like ‘movable array names’
   –   Index them (like an array) to access data: pW0[4]
   –   Use them (like an array) as string variables
   –   BUT you can move them using integer math
   –   BUT they do not reserve (jargon: allocate) any elements

• Pointers are VERY POWERFUL & DANGEROUS!
   – ! C pointers let you read/write ANYWHERE in memory !

								
To top