In this tutorial, we will learn how to declare a string and initialize it using example.

Declaration of string


char variable_name[size];


char name[10];
char city[20];

Initialization of string

There are multiple ways we can initialize a string.

Direct initialization

If we assign string directly with in double quotes, no need to bother about null character.

Because compiler will automatically assign the null character at the end of string.

i)Assigning direct string with size

char country[6]=india;


while giving initial size, we should always give extra one size to store null character.

To store "india", string size 5 is enough but we should give extra one (+1) size 6 to store null character.

In general to store N character string, we should create N+1 size char array.

ii)Assigning direct string without size


char country[]=india;

In the above case, string size will be determined by compiler.

Character by character initialization

we can also assign a string character by character.

If we assign character by character , we must specify the null character '\0' at the end of the string.

i)char by char with size


char country[6]={i,n,d,i,a,’\0};

ii)char by char without size


char country[]={i,n,d,i,a,’\0};

Pictorial Explanation

strings in C

All four methods are perfectly valid.

Topics You Might Like