A C string is a sequence of characters placed with a null terminator (\0) at the end and placed within double quotes. Strings are useful for storing text or a group of characters. Unlike other programming languages, C programming does not have a string data type. So, we must use the char data type to create a one-dimensional array of characters to create a string.
A one-dimensional array of characters end with a null character \0 is called a string in C Programming. They play a vital role in reading user input text, writing information to files, etc. Let us see how to declare a string, initialize, access elements or characters, modify a string, and print characters with examples.
Declaration of a string in C
There are multiple options to declare a string, and all of them are valid. The syntax of a string declaration in C Programming is as follows.
char Name[Size];
- Name: Please specify the name. For example, full_name, employee_name, etc.
- Size: Number of characters required for this plus one (\0). For instance, if Size =10, it can hold 9 characters.
For Example,
char full_name[50];.
Here, full_name is the string name, and the size equals 50. It means this allows a maximum of 49 characters.
Basic Declaration
Here, we have declared a C string with a fixed size of 10. It means the below string has the capacity to store 9 characters and one null terminator (\0). We have not initialized the string; it simply allocates memory, and memory contains garbage values.
char s[10];
C string Declaration with Initialization
In the line below, we have declared a string with a fixed size of 10 and initialized it to the word ” Happy “. It allocates memory to store 10 characters (including the null character, \0). As there are only five characters in the word ” Happy “, it is stored in memory and appended \0 at the end. A total of six bytes are utilized, and the remaining memory is unused.
char s[10] = "Happy";
C String Declaration without Size
Here, we have declared a string without mentioning a fixed size and initialized a text to it. The compiler checks the total number of characters and automatically calculates the size as six bytes (including the null terminator).
char s[10] = "Happy";
In all the above examples, the compiler adds the null terminator to the end to mark the end.
Pointer-based Declaration of a String in C
In the string declaration below, s is a pointer stored in read-only memory pointing to a string literal.
char *s = "New";
NOTE: Defining a string means declaring a character array and initializing it with some text in a single step. For example, char s[] = “hi”;
C String Initialization Techniques
Once the string declaration is complete, the next step is to initialize it with a text for performing string operations.
In the previous section, we showed multiple options for declaring a string, and in some examples, we have initialized the strings. This section covers multiple options for initializing a string.
Using a string literal
In the example below, we initialized a C string without a fixed size. It is the most common way of declaring a string because the compiler decides the string size at compile time. It counts the total number of characters in the initialized text plus one null character (\0) as a string size. Here, it is 17.
TIP: We must use the double quotes to initialize the string.
char name[] = "Tutorial Gateway"; // Declare without Size
Character by Character Initialization
Apart from the above mentioned ones, we can initialize a C string character by character. However, we must explicitly include the null character (\0). In the code below, the first one is initializing a string (character by character) without a fixed size. The next one has a fixed size that fits the given individual character, along with the null terminator.
char name[] = {'T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 'G', 'a', 't', 'e', 'w', 'a', 'y', '\0'};
char name[16] = {'T', 'u', 't', 'o', 'r', 'i', 'a', 'l',' G', 'a', 't', 'e', 'w', 'a', 'y', '\0'};
Partial Initialization of a C string
It is a common scenario in the programming world. We declared a string with a fixed size of 50 and initialized a string with a length of 16 characters plus one null terminator. It means the remaining space is unused.
char name[50] = "Tutorial Gateway"; // Declare with Size
C string initialization using pointers
We can also declare a string using pointers and initialize it to a text.
char *name = "hello world";
Dynamic Initialization
There are situations where we declare a C string with a fixed or dynamic size. Next, we allow users to add individual characters to a string dynamically. For instance, in the example below, we declared a string of size 10. Next, we used the index positions to assign individual characters. Remember, we must explicitly add the null terminator at the end.
char s[10];
s[0] = 'N';
s[1] = 'e';
s[2] = 'w';
s[3] = '\0';
How to display or print a string in C?
The printf() statement is the common way to display the result in the console. However, there are different format specifiers for displaying different data types. For instance, to display a string, we must use the %s format specifier. The program below prints all characters in a str string from start to end except the null terminator (\0).
#include <stdio.h>
int main()
{
char str[] = "New Year";
printf("%s", str);
}
New Year
Puts Example
The following example uses the puts() function to print a string in C.
#include <stdio.h>
int main()
{
char str[] = "Happy New Year";
puts(str);
}
Happy New Year
C Program to Declare, Initialize, and Print String
In this program, we declared and initialized the string or character array in all possible ways. Next, we use the printf statement with the %s format specifier to print the string as the output. I suggest you refer to the Array article.
In the first two string declarations, the compiler automatically adds the null terminator to mark the string endpoint. However, for character arrays, we must explicitly add the null character.
TIP: You must use %s to display the sentence or text as output. Or you can use the C Programming puts function.
#include <stdio.h>
int main(int argc, const char * argv[]) {
// Without Size
char name1[] = "Tutorial Gateway";
// With Size
char name2[50] = "Tutorial Gateway";
// Declare Characters Array
char name3[] = {'T','u','t','o','r','i','a','l','G','a','t','e','w','a','y', '\0'};
char name4[16] = {'T','u','t','o','r','i','a','l','G','a','t','e','w','a','y', '\0'};
printf("Name1: %s \n", name1);
printf("Name2: %s \n", name2);
printf("Name3: %s \n", name3);
printf("Name4: %s \n", name4);
return 0;
}

Memory Representation of a string in C
When we declare a string and initialize it to a word(s), it allocates memory to store those characters. Understanding memory is key to accessing the complete string or character at a specific index position.
To demonstrate it, we declared a string without size and initialized it to a word of two characters.
char s[] = "We";
The table below shows the underlying memory layout for the C string mentioned above.
| Index | Value |
|---|---|
| 0 | W |
| 1 | e |
| 2 | \0 |
If you observe the above table, the memory required to store the given string is 3 bytes because each character requires a single byte. Each string ends with a null terminator (\0), and it requires an extra byte. In short, we can say that the total memory required is equal to the total number of characters in a string (including spaces) plus one.
Access Elements of a String in C programming
As we mentioned earlier, a string is a character array and behaves like a regular array. In the memory representation section, we have shown how each character in a string is stored based on the index and value. For example,
char s[] = "We";
It means there are characters in a given string, and each has a unique index position starting from 0 to n, where n is a null terminator (\0). Here, s[0] -> W and s[1] -> e.
In the example below, we declared a C string with the word Boss. In the next line, we use the index position to access the second character in a string (index position 1). The % c format specifier helps to print a single character.
#include <stdio.h>
int main()
{
char s[] = "Boss";
char c = s[1];
printf("%c", c);
}
o
Use a while loop to access all characters in a C string
As we mentioned earlier, we can use index positions to access individual letters. By this index, you can perform insert, delete, or update any string character at any given position. Here, the while loop starts iterating from the first character and moves until it finds the null character.
#include <stdio.h>
int main(int argc, const char * argv[])
{
char name[50];
int i = 0;
printf("Please enter the Name : ");
scanf("%s", name);
while (name[i] != '\0')
{
printf("The Character at %d Index Position = %c \n", i, name[i]);
i++;
}
return 0;
}

The analysis of the C String or character array iteration-wise is shown below.
First Iteration : while (name[i] != ‘\0’)
Here, the value i = 0. It means, name[0] = h So, condition is True
It will print that letter along with the index position.
Next, the value i will increment
Second Iteration: while (name[1] != ‘\0’)
while (e != ‘\0’) – Condition True
C string Third Iteration: while (name[2] != ‘\0’)
while (l != ‘\0’) – It means the condition was True.
Fourth Iteration: while (name[3] != ‘\0’)
while (l != ‘\0’) – Condition True
Fifth Iter: while (name[4] != ‘\0’)
while (0 != ‘\0’) – This condition is True
Sixth Iteration: while (name[5] != ‘\0’)
while (\0 != ‘\0’) – Condition is False. So, the Compiler will exit from the While loop.
Loop through a C string using a for loop
Similar to the while loop, we can use a for loop to iterate over the characters in a string. While iterating the string characters, we can perform string operations on individual characters based on a condition, and so on.
In the example below, the for loop starts from 0 (default index position) and runs until it reaches the null terminator (\0). Once it finds the null characters, the compiler will exit from a for loop. Inside a for loop, we used the printf() to print the index position and the character at that position.
#include <stdio.h>
int main()
{
char str[] = "Boss";
for(int i = 0; str[i] != '\0'; i++)
{
printf("Index = %d and Value = %c\n", i, str[i]);
}
}
Index = 0 and Value = B
Index = 1 and Value = o
Index = 2 and Value = s
Index = 3 and Value = s
Instead of using the null terminator as the loop condition, we can use the string length. Please replace the str[i] != ‘\0’ condition inside the for loop with the code below.
int length = strlen(str);
for(int i = 0; i < length; i++) {
Traverse a C string using a pointer
In the above two examples, we declared and initialized strings and used while loops and for loops to traverse the string characters. However, we can use pointers to traverse the string characters.
In the example below, we initialized a string using a pointer. As the pointer to the address of the first character in a string. Within the for loop, the condition checks whether the character is a null terminator (end of a string). If not, the iteration continues. Within the loop, we used the %c to print the character at that position and increment the pointer position to the next character.
#include <stdio.h>
int main()
{
char *str = "Race";
while(*str != '\0')
{
printf("%c ", *str);
str++;
}
}
R a c e
How to Modify Characters in a C string?
We can use the index positions of the string characters to alter/modify individual characters. In the example below, we declared a string without a size and initialized the word “Boss”. The str[0] will access the first character inside the str string and assign it to a new character T. It means, the code replaces the first character ‘B’ in the str string with the ‘T’ character, and the word becomes Toss.
char str[] = "Boss";
str[0] = 'T';
printf("%s", str);
Toss
NOTE: We can not change the strings declared as pointers.
Use printf() and scanf() to read and write string in C
The standard way of reading the user input and writing a string to the console is by using the printf() and scanf() statements. Here, scanf() allows the user to enter the required string. Next, the printf() statement prints or write string.
The below scanf() approach works fine when the input string is a single word. If you pass a two-word statement or string (Nelson Jr), the scanf() reads the text before the blank space. To resolve this, we must use the gets() function to read the text.
#include <stdio.h>
int main()
{
char name[50];
printf("Enter Name = ");
scanf("%s", name);
printf("%s", name);
}
Enter Name = Nelson
Nelson
If we use a scanset (regular expression) inside a scanf() statement, it will read a string with blank spaces. Please replace the scanf statement in the above example with the line below, and the program will read text with spaces.
scanf("%[^\n]s", name);
C String input and output functions (gets and puts)
When working with strings, it is important to understand the built-in string functions required to read the input string and print it to the console. In the C programming language, gets() and puts() functions are useful for reading user input strings and printing output.
#include <stdio.h>
int main()
{
char str[50];
printf("Enter Text = ");
gets(str);
puts(str);
}
Enter Text = Welcome again
Welcome again
Although the gets() function works seamlessly, it does not consider whether the user-given text fits into the declared string. The safest way to read the user-given string is using the fgets() function. The fgets() function reads multi-line text without any issues.
#include <stdio.h>
int main()
{
char str[15];
printf("Enter Text = ");
fgets(str, sizeof(str), stdin);
puts(str);
}
Enter Text = Hello Guys
Hello Guys
If we enter more text than it fits. Let me enter the following text and observe the output. The fgets() function only reads 14 characters from the given input string because str is of 15 bytes and one is reserved for the null terminator. It allows only 14 characters.
Enter Text = Tutorial Gateway
Tutorial Gatew
TIP: Use the fgets() function to read a string and the puts() function to write a string.
Empty string in C programming
A string containing only the null terminator (\0) is called the empty string. We can declare and initialize an empty string without any issue. There are multiple ways we can declare an empty string.
char s1[] = "";
char s2[10] = "";
char s3[10] = {'\0'};
The compiler appends the null character to the first two statements. In the third line, we must explicitly add the null terminator. We can use the if statement with a null terminator or the strlen() function to check for empty strings.
#include <stdio.h>
int main()
{
char s[] = "";
if(s[0] == '\0')
{
printf("Empty String");
}
}
Empty String
Otherwise, use the strlen() function to find the length of an empty string. If the string length is zero, it is an empty string. Please replace the if statement in the above program with the one below.
if (strlen(str) == 0)
Passing strings to functions
Similar to any other variable, we can pass a C string or character array to a function as an argument. By passing a string to functions, we can perform various string operations within the functions.
There are two ways to pass a string to functions: pass it as a character array or as a pointer. In the following example, we will demonstrate the two possible options to pass a string to functions.
In the example below, we passed a character array (String) as a function parameter that prints the given string as output. In the next function, we passed a string as a pointer, and it calculates the total number of characters in a given string using the strlen() function.
TIP: In both options (s[] and *s), they receive a pointer to the first character in a string.
#include <stdio.h>
#include <string.h>
void printing(char s[]) {
printf("String = %s\n", s);
}
void length(char *s) {
int len = strlen(s);
printf("Length = %d\n", len);
}
int main() {
char name[] = "John Wick";
printing(name);
length(name);
}
String = John Wick
Length = 9
Strings and pointers
We have already shown how to traverse a string using a pointer. In this section, we show the process of accessing the C string characters using a pointer.
When we initialize a string using a pointer or access the string using a pointer variable, we must be careful when accessing the characters. When working with pointers, they point to the memory address of the first string character by default. So, when we call *name, it will print the first string character (H). When we say *(name + 6), add six to the memory address of the first character, and it will be the seventh character inside a string.
#include <stdio.h>
int main()
{
char name[50] = "Hello World";
printf("%c\n", *name);
printf("%c\n", *(name + 1));
printf("%c\n", *(name + 6));
printf("%c\n", *(name + 9));
}
H
e
W
l
C String literal vs character array
As we already know, a character array is nothing but a string, and we explain the difference between it and a string literal. In all our previous examples, we have seen both a character array and a string literal, but you may not notice.
A string literal is a sequence of characters or numbers enclosed in double quotes. Once a string literal is defined, we can’t change it. For instance, in the example below, name is a string (character array) and “Hello World” is a string literal.
The statement below declares a string of size 50, and because of the initialization, it stores characters of the “Hello World” text inside memory along with a null terminator. As the C string literal is stored inside permanent memory, we can perform update and delete operations on the text.
char name[50] = "Hello World";
If we initialize a string using a pointer, things become different. The statement below creates a pointer pointing to a string literal. It means the string literal is stored in read-only memory, so update and delete operations are not possible.
char *name = "Hello";
Array of Strings
This programming language allows storing multiple strings in one variable. We can declare a C string that accepts an array of strings (a multidimensional string). The syntax to store an array of strings is
char name[strings][size];
In the above syntax,
- Strings: The total number of strings you want to store under the name variable.
- Size: The maximum size of each string. Any individual string should not be more than this length. If size = 10 means the total number of characters in every string inside the array must be less than 10.
In the example below, we declared a variable that stores an array of strings. Here, it allows four strings, and the length of each string should be less than 10.
#include <stdio.h>
int main()
{
char str[4][10] = {"Milk", "Bread", "Cheese", "Butter"};
for (int i = 0; i < 4; i++)
{
printf("%s\n", str[i]);
}
}
Milk
Bread
Cheese
Butter
C string Common mistakes
Although strings are easy to understand and simple to work with, many misunderstandings lead to errors. This section covers the most common errors.
Forgetting the Null Character (\0)
If the C string declaration and initialization happen in the ways mentioned below, there is no need to worry about the null terminator. The compiler will take care of it and add it automatically.
char s[] = "Happy"; char s[10] = "Happy";
However, if we use the character array for the initialization, we must explicitly add the null terminator. In the example below, we declared a character array without a fixed size. Next, we used characters without mentioning the null terminator.
#include <stdio.h>
int main()
{
char s[] = {'H', 'i'};
printf("%s", s);
}
It will print a garbage value based on the IDE.
HiHp<-�
To overcome this, we must explicitly mention the null terminator to mark the string endpoint.
#include <stdio.h>
#include <string.h>
int main()
{
char s1[] = {'H', 'a', 'p', 'p', 'y', '\0'};
char s2[20] = {'H', 'a', 'p', 'p', 'y', '\0'};
printf("%s", s1);
printf("\n%s", s2);
}
Happy
Happy
Assigning values to a C string using the = operator
Once the string (character array) is declared, we can’t use the assignment operator (=) to assign a string literal. In the example below, we declare a string name with a size of 50. In the next line, we used the equal to operator to assign the string literal (John). However, the character array will not accept this kind of initialization.
#include <stdio.h>
int main(){
char name[50];
name = "John";
printf("%s", name);
}
Error
To overcome these errors, we must use the strcpy() or strncpy() functions. Here, we used the strcpy() function to copy the text into a string.
#include <stdio.h>
#include<string.h>
int main(){
char name[50];
strcpy(name, "John");
printf("%s", name);
}
John
Wrong ways to initialize a string in C
In the example below, we declared a string that accepts five bytes. However, the initialized string has 5 characters (Happy). It means there is no memory space for the null terminator (\0), which is a wrong way of string initialization.
char s[5] = "Happy";
The other way is trying to fit a larger number of characters inside a small string size. Here, we declared a string that can hold 4 bytes (3 characters and one null terminator). However, we initialized it to a string of 5 characters, which is illegal.
char s[4] = "Happy";
Modifying the string literal (pointer)
Unlike regular string variables, we can’t modify the text or characters within the string literal. In other words, once the string is initialized using a pointer, we cannot change the characters of that string.
#include <stdio.h>
int main()
{
char *s = "Boss";
s[0] = 'T';
printf("%s", s);
}
Segmentation fault
Real-time examples of C string
The following are some real-time examples where strings are useful.
How to find the ASCII value of a string character?
As we all know, each alphabet (both upper and lowercase) has a distinct ASCII value. When we use the %c format specifier, it will print the character at that index position. However, if we use the %d format specifier, the printf() statement prints the ASCII value of the character at that index position.
In the example below, the first statement prints the character at the first index position (H). The next statement prints the ASCII value of H.
#include <stdio.h>
int main()
{
char name[10] = "Hello";
printf("%c ", name[0]);
printf("%d", name[0]);
}
H 72
NOTE: Multiple examples can explain various string operations. However, we have a dedicated article explaining them. Please refer to the string functions article to see the operations. Next, visit the string programs section under the programs page to see the manual approaches for each operation.
How to find the length of string C?
In this program, we are using the built-in function strlen to find the length of a char array.
#include <stdio.h>
#include <string.h>
int main(int argc, const char * argv[])
{
char nam[50];
printf("Enter the Name : ");
scanf("%s", nam);
float len;
len = strlen(name);
printf("The Length = %.f \n", len);
return 0;
}

How to find the size and length of a string?
When working with the strings, people often confuse the length and the size of a string. To clear differences, in this program, we declared a string that can store up to 49 characters plus a null terminator. Initialized that string with the word Happy New Year”.
We used the built-in strlen() function to calculate the total number of characters in a given string, also called string length. It will return the count of total existing characters excluding the null terminator (\0). However, the sizeof() function returns the actual size, which is 50.
#include <stdio.h>
#include <string.h>
int main()
{
char s[50] = "Happy New Year";
printf("%s \n", s);
printf("%ld \n", sizeof(s));
printf("%ld", strlen(s));
}
Happy New Year
50
14
Login Username checking
The following C string program allows the user to enter the username. The If Else statement uses the strcmp() function to compare the original username against the user-entered text. If both are the same, print login successful. Otherwise, print Wrong Username message.
#include <stdio.h>
#include<string.h>
int main()
{
char original[] = "admin";
char username[25];
printf("Enter Username = ");
scanf("%s", username);
if(strcmp(original, username) == 0) {
printf("Login Successful");
}
else {
printf("Wrong Username");
}
}
Enter Username = admin
Login Successful
Enter Username = hello
Wrong Username
Basic Email Validation
In the example below, we used the strchr() function multiple times, joined by the logical AND operator. It checks whether the given email contains the @ and . symbols. If true, it is a valid email.
#include <stdio.h>
#include<string.h>
int main()
{
char email[] = "contact@tutorialgateway.org";
if(strchr(email, '@') && strchr(email, '.')) {
printf("Valid Email");
}
else {
printf("Invalid");
}
}
Valid Email