# Strings.

## Pointers to strings.

C does not have a "string" datatype. To create a string you have to use a char array or a char pointer. If you are not familur with char arrays I recomend that you read about them now.

To recap, a char pointer is defined like this:

         main()
         {
           char *Text;
         }

All this program does is reserve storage that will hold an address. At this point the address could be anything. To initalize Text you can code:

         main()
         {
           char *Text = "Thunder";
         }

Text now has the address of the first character in Thunder. Graphically, things look like this.

          (Address) (Data)

               ---- ----
              | F1 | 00 <------- Text
    	  |----|----|               (Data) (Adress)
              | F2 | 00 |                 -------------
    	  |----|----|         -------> 54 (T) | D1 |
    	  | F3 | 00 |        |       |--------|----|
    	  |----|----|  *Text |       | 68 (h) | D2 |
    	  | F4 | D1 | -------        |--------|----|
    	   ---------                 | 75 (u) | D3 |
    	                             |--------|----|
    				     | 6E (n) | D4 |
    				     |--------|----|
                                         | 64 (d) | D5 |
                                         |--------|----|
                                         | 65 (e) | D6 |
                                         |--------|----|
                                         | 72 (r) | D7 |
                                         |--------|----|
                                         | 00     | D8 |
                                          -------------

Please note the 00 at the end of Thunder. This is the NULL character and is used to mark the end of a string.

If we wanted to O/P the data pointed to by a char pointer we can code.

Source
         main()
         {
           char *Text1 = "Thunder";          /* Define and initalize */
           char *Text2;                      /* Define only          */

           Text2 = "Bird";                   /* Point to some text   */

           printf("%s%s\n", Text1, Text2);
         }
Result
          ThunderBird

This is all very well, but there is a MAJOR problem! Thunder and Bird are constants, they cannot be changed in anyway. We need a method of pointing to some storage that can be altered and true to form, C provides a function called malloc to do just that.

## See Also:

VOID keyword.

Top | Master Index | Keywords | Functions