Strings as an array of Characters


A string is defined as an array of characters. Strings are terminated by the special character ‘\o’; this is called a null parameter or null terminator. When you declare the string, you should ensure that you should have sufficient room for the null terminator. The null terminator has ASCII value 0.


int main ( )
	char s1[9]; //A
	char s2[6] = {'H', 'e', 'l', 'l', 'o'};   //B

	int count = 0;
	char ch;

	while ((ch = getchar()) && ch!='#' && count <8) //C
		s1[count++] = ch;
        // insert \0 at last to end string
	s1[count] = '\0'; // D

	printf("String 1 %s",s1);
	printf("String 2 %s",s2);
	return 0;


  1. In statement A, The size of the string is 9, So, 9 is the last element terminator, so you can use only 8 positions.
  2. In statement B, the string “Hello” is assigned so that the array elements are H e l l o \0
  3. In statement B, The null terminator is appended automatically.
  4. Statement B puts the data in a string using standard array notation.
  5. You can print a string using the placeholder %s; the string is printed until it encounters a null character.
  6. In statement C, The while loop inputs the string by reading character by character.
  7. The function getchar returns the input character from keyboard.
  8. Note that the counter is incremented up to 8 so as to accommodate the last null terminator.
  9. The null terminator is put in place by statement D.
  10. The while loop can be terminated before counter n by putting in the # character.

Points to Remember

  1. A string is a character array with a null terminator at the end.
  2. You can initialize the array using different methods.