How To Define, Declare, and Initialize a String in C
In this tutorial, we are going to see how to define, declare, and initialize a string in C. A string can be defined as an array of characters ending with the null character (‘\0’). The string array is used to manipulate text such as a word or sentences. Each character of the array occupies one byte of memory. The end character (‘\0’) is important in a string, because it is the only way to identify where the string ends.
Example :
char str[] = "StackHowTo";
When the compiler encounters a sequence of characters in quotes, it adds the character ‘\0’ at the end by default.
How To Declare a String in C
Here is how you can declare strings:
char c[6];
Here we have declared a string of 6 characters.
How To Initialize a String in C
You can initialize a string in different ways.
char c[] = "StackHowTo"; char c[11] = "StackHowTo"; char c[] = {'S','t','a','c','k','H','o','w','T','0','\0'}; char str[11] = {'S','t','a','c','k','H','o','w','T','0','\0'};