Strings in C

In this class, we will try to understand Strings in C.

In our early classes, we have discussed characters data types.

Strings in C

A character variable, In the c programming language, is declared by char data type.

For example, consider the following declaration char c = ‘a’;.

In the above declaration, c is a character variable to store one character.

Table of Contents

Strings

In the same way, can we store a sequence of characters or strings in c?

Yes, the c programming language has a facility to store a sequence of characters or strings.

The c programming language considers the string as an array of characters.

To declare a string, we have to use ‘an array of character data types and the string to be stored in double-quotes.

String Declaration

The image below is an example declaration of the string.

Strings in C Declaration
Strings in C Declaration

C Programming Language considers the string as an array of characters.

The characters of a string are stored as the elements of an array, as shown in the image below.

Strings in C Visualization
Strings in C Visualization

If we closely observe the above declaration, the string has 15 characters, but we have assigned 16 characters.

We have done that because extra space is used to create the null character by the compiler at the end of the string.

The creation of the null character states to the compiler the end of the string.

Whenever we want to declare a string, we have to provide an extra space greater than string.

If we didn’t know or didn’t want to count the characters in the string, c provides another kind of declaration, as shown in the image below.

Strings in C Declaration Without Number of Characters
Strings in C Declaration Without Number of Characters

In the above declaration, the c compiler will automatically provide extra space at the end of the string.

What if the number of characters is less than the size of an array.

Strings in C Declaration Number of Characters Less
Strings in C Declaration Number of Characters Less

The compiler will store the remaining spaces with null characters.

Strings in C Declaration Number of Characters Less Visualization
Declaration of Number of Characters Less Visualization