Ramesh.B & Ravi Kishore.Ch Page 2
When string literals are used in the program, C automatically creates an array of characters initializes it to a null-
delimited string and stores it, remembering is address. It does all this because we use the double quotes that
immediately identify the data as a string value.
Referencing String Literals
A string literal is stored in memory. It has an address. Thus, we can refer to a string literal by using pointers.
The literal, since it is an array of characters, is itself a pointer constant to th first element of string. Generally when we
use it, we are referring to the entire string. It is possible, to refer only one of the characters in the string.
Ex:void main()
{
printf(“%s”, “Hello”);
printf(“\n%c”, “Hello”[1]);
}
Output
Hello
e
Declaring Strings
C has no string type. As it is defined as sequence of characters, it is stored using character array. The storage
structure, must be one byte larger than the maximum data size because there is a delimiter at the end.
Ex : A string of 8 characters length can be declared as
char str[9];
String definition defines memory for a string when it is declared as an array in local memory. We can also declare a
string a pointer. When we declare the pointer, memory is allocated for the pointer, no memory is allocated for the
string itself.
Ex : char *pStr;
Initializing Strings
A string can be initialized by assigning a value to it when it is defined.
Ex : char str[9] = “Good day”;
Since a sting is stored in an array of characters, we do not need to indicate the size of the array if we initialize.
Ex : char str[] = “C Program”;
In the above case, the compiler will create an array of 10 bytes and initializes it with “C Program” and a null character.
If we now tried to store “Programming” in str array it is not possible as the length is not sufficient. So, a string
variable is initialized with a longest value.
C provides two more ways to initialize strings. A common method is to assign a string literal to a character pointer.
Ex : char *pStr = “Hello World”;
We can also initialize a string as an array of characters. This method is not used too often because it is so tedious to
code.
Ex: char str[12] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’, ‘\0’ }
Strings and Assignment Operator
Since, the string is an array, the name of the a string is a pointer constant. So therefore a string cannot be
used as the left operand of the assignment operator.