String Definition
A string can be defined using a character array or a pointer to characters. Although the two definitions look similar, they are actually different.
Example
#include<stdio.h> int main ( ) { char * s1 = "abcd"; // A char s2[] = "efgh"; // B printf( "%s %16lu \n", s1, s1); // C printf( "%s %16lu \n", s2, s2); // D s1 = s2; // E printf( "%s %16lu \n", s1, s1); // F printf( "%s %16lu \n", s2, s2); // G getchar(); return 0; }
Explanation
- Statement A declares s1 as a pointer to a character. When this definition is encountered, the compiler allocates space for the string abcd; the base address of the string is assigned to s1, which is the pointer variable.
- Statement B declares s2 as a character array. The size of the array is 5 because of an additional null terminator in this case. Also, a space of 5 characters is allocated and the base address is given to s2, which is the pointer constant. During the lifetime of the program, we cannot change the value of s2.
- The allocation for s1 is the allocation required by the pointer variable.
- Statement C prints s1, using two place holders: %s and %16lu. Using %s, you will print the string as “abcd”. Using %16lu you will print the base address of the string.
- Statement E assigns a base address of s2 to s1; that is possible because s1 is a variable.
Point to Remember
- When the string is declared as a character pointer, a space is allocated for the pointer variable, which holds the base address of the string.