C Language | Arrays | Strings

This article explains how to store strings in variables. A string is an array of characters and can be managed with a char array.

Storing Strings in Variables

C does not provide a dedicated string type. A string is a sequence of character codes, so an array is the natural way to represent it.

Code 1

#include <stdio.h>

int main() {
 char chStr[6];
 int iCount;

 chStr[0] = 'K';
 chStr[1] = 'i';
 chStr[2] = 't';
 chStr[3] = 't';
 chStr[4] = 'y';
 chStr[5] = '\n';

 for(iCount = 0 ; iCount < 6 ; iCount++)
   printf("%c" , chStr[iCount]);
 return 0;
}

Code 1 stores one character in each array element and prints the characters one by one. This works, but the program must track the number of characters.

C strings solve this problem by ending with a zero byte.

Code 2

#include <stdio.h>

int main() {
 char chStr[7];
 int iCount;

 chStr[0] = 'K';
 chStr[1] = 'i';
 chStr[2] = 't';
 chStr[3] = 't';
 chStr[4] = 'y';
 chStr[5] = '\n';
 chStr[6] = 0;

 for(iCount = 0 ; chStr[iCount] ; iCount++)
   printf("%c" , chStr[iCount]);
 return 0;
}

The final zero is called the null character. Standard C functions follow the same convention. A string literal such as "Kitty" is stored as six elements: five characters followed by a null character.

Use %s with printf() to print a character array until its null character.

Code 3

#include <stdio.h>

int main() {
 char chStr[7];

 chStr[0] = 'K';
 chStr[1] = 'i';
 chStr[2] = 't';
 chStr[3] = 't';
 chStr[4] = 'y';
 chStr[5] = '\n';
 chStr[6] = 0;

 printf("%s : %s" , "Kitty" , chStr);
 return 0;
}

When passing chStr to printf(), specify the array name without an index. An array name represents the beginning of the array, or more precisely, the address of its first element. Arrays and pointers are closely related.