Strings and character arrays in C programming

In this tutorial, we will  learn about strings and character arrays with example.

Characters arrays


Characters arrays are similar to normal arrays. 

character arrays can be initialized in the normal way using an  list. For Example :

char letters[] = { ’l’, ’i’, ’v’, ’e’ };

They can be also initialized with strings. But array will contain last element ‘\0’ character.

char letters[] = "live"; //not recommended

This will be equivalent to:

char letters[] = { ’l’, ’i’, ’v’, ’e’, ’\0’ };

String


string is a sequence of characters which is treated as a single data item in C. 

String constants are allocated in memory and has address and can be refereed by char * pointer. But other constant like float, array doesn’t has this property. For example:

double *val= 5.1; /* Invalid and Won’t compile. */
int *parray= { 11, 22, 33 }; /* Invalid and Won’t compile. */

But, is valid for String.

char *str = "live on code";

Strings can be directly copied to another variable if it is initialized as char arrray. If not string must be manually copied character by character.