> ~ Online tutorial


Strings, Arrays and Pointers
A string is really an array of characters. It is stored at some place the memory and is given an end marker which standard library functions can recognize as being the end of the string. The end marker is called the zero (or NULL) byte because it is just a byte which contains the value zero: \0. Programs rarely gets to see this end marker as most functions which handle strings use it or add it automatically.
Strings can be declared in two main ways; one of these is as an array of characters, the other is as a pointer to some pre-assigned array. Perhaps the simplest way of seeing how C stores arrays is to give an extreme example which would probably never be used in practice. Think of how a string called string might be used to to store the message "Tedious!". The fact that a string is an array of characters might lead you to write something like:
#define LENGTH 9;

main ()

{ char string[LENGTH];

string[0] = 'T';
string[1] = 'e';
string[2] = 'd';
string[3] = 'i';
string[4] = 'o';
string[5] = 'u';
string[6] = 's';
string[7] = '!';
string[8] = '\0';

printf ("%s", string);
}

This method of handling strings is perfectly acceptable, if there is time to waste, but it is so laborious that C provides a special initialization service for strings, which bypasses the need to assign every single character with a new assignment!. There are six ways of assigning constant strings to arrays. (A constant string is one which is actually typed into the program, not one which in typed in by the user.) They are written into a short compilable program below. The explanation follows.
/**********************************************************/
/*                                                        */
/* String Initialization                                  */
/*                                                        */
/**********************************************************/

char *global_string1 = "A string declared as a pointer";

char  global_string2[] = "Declared as an array";


main ()

{ char *auto_string = "initializer...";

  static char *stat_strng = "initializer...";

  static char statarraystr[] = "initializer....";


/* char arraystr[] = "initializer....";  IS ILLEGAL! */
/* This is because the array is an "auto" type       */
/* which cannot be preinitialized, but...            */

  char arraystr[20];

printf ("%s %s", global_string1, global_string2);
printf ("%s %s %s", auto_string, stat_strng, statarraystr);
}

               /* end */

The details of what goes on with strings can be difficult to get to grips with. It is a good idea to get revise pointers and arrays before reading the explanations below. Notice the diagrams too: they are probably more helpful than words.

Please Give Us Your 1 Minute In Sharing This Post!
Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Powered By: BloggerYard.Com

0 comments: