C Strings - Declaring Strings in C

Learn via video course
FREE
View all courses
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
Topics Covered

In C programming, a string is essentially an array of characters terminated by the null character '\0'. Unlike a generic character array, a C string always concludes with this unique terminator, indicating its endpoint. Represented as a one-dimensional array, each character within occupies one byte of memory. For instance, when declaring "char s[10]", the array is implicitly initialized with a null terminator. This distinct characteristic ensures that operations on C strings rely on this sentinel value to determine string boundaries, facilitating efficient string manipulation and processing in C programs.

Declaring a String in C

A String in C is an array with character as a data type. C does not directly support string as a data type, as seen in other programming languages like C++. Hence, character arrays must be used to display a string in C. The general syntax of declaring a string in C is as follows:

Thus, the classic declaration can be made as follows:

It is vital to note that we should always account for an extra space used by the null character(\0).

Highlights:

  1. Character arrays are used for declaring strings in C.
  2. The general syntax for declaring them is:

Initializing a String in C

There are four methods of initializing a string in C:

1. Assigning a string literal with size

We can directly assign a string literal to a character array keeping in mind to keep the array size at least one more than the length of the string literal that will be assigned to it.

Note While setting the initial size, we should always account for one extra space used by the null character. If we want to store a string of size n, we should set the initial size to be n+1.

For example:

The string length here is 7, but we have kept the size to be 8 to account for the Null character. The compiler adds the Null character(\0) at the end automatically.

Note: If the array cannot accommodate the entire string, it only takes characters based on its space. For example:

Output:

2. Assigning a string literal without size

It is also possible to directly assign a string literal to a character array without any size. The size gets determined automatically by the compiler at compile time.

The critical thing to remember is that the name of the string, here "str" acts as a pointer because it is an array.

3. Assigning character by character with size

We can also assign a string character by character. However, it is essential to set the end character as '\0'. For example:

4. Assigning character by character without size

Like assigning directly without size, we also assign character by character with the Null Character at the end. The compiler will determine the size of the string automatically.

Assigning character by character without size

Highlights: There are four methods of initializing a string in C:

  1. Assigning a string literal with size.
  2. Assigning a string literal without size.
  3. Assigning character by character with size.
  4. Assigning character by character without size.

Assign value to strings

Character arrays cannot be assigned a string literal with the '=' operator once they have been declared.

This will cause a compilation error since the assignment operations are not supported once strings are declared. To overcome this, we can use the following two methods:

  1. Assign the value to a character array while initializing it, explained above.
  2. We can use the strcpy() function to copy the value we want to assign to the character array. The syntax for strcpy() is as follows:

It copies the string pointed by the source (including the null character) to the destination. For example:

This assigns the value to the string.

Note - It is vital to make sure the value assigned should have a length less than or equal to the maximum size of the character array.

Highlights:

  1. Character arrays cannot be assigned a string literal with the '=' operator once they have been declared.
  2. Assignment can either be done at the initialization time or by using the strcpy() function.

Read String from the user

The most common operation used for reading a string is scanf(), which reads a sequence of characters until it encounters whitespace (i.e., space, newline, tab, etc.). The following section explains the method of taking input with whitespace. For example,

If we provide the following input:

We get the following Output:

As we can see, scanf() stops taking input once it encounters whitespace.

Note -

  1. The format specifier used to input and output strings in C is %s.
  2. You might notice that generally, the variable's name is preceded by a & operator with scanf(). This is not the case here, as the character array is a pointer that points to the address of the first character of the array. Hence the address operator (&) doesn't need to be used.

Highlights:

  1. Strings in C can be read using scanf(). However, it only reads until it encounters whitespace.

How to read a line of text?

The scanf() operation cannot read strings with spaces as it automatically stops reading when it encounters whitespace. To read and print strings with whitespace, we can use the combination of fgets() and puts():

  • fgets() The fgets() function is used to read a specified number of characters. Its declaration looks as follows:

name_of_string*: It is the variable in which the string is going to be stored. number_of_characters: The maximum length of the string should be read. stdin: It is the filehandle from where the string is to be read.

  • puts() puts() is very convenient for displaying strings.

name_of_string: It is the variable in which the string will be stored.

An example using both functions:

Input:

Output:

In the above example, we can see that the entire string with the whitespace was stored and displayed, thus showing us the power of fgets() and puts().

Highlights:

  1. The combination of fgets() and puts() is used to tackle the problem of reading a line of text with whitespace.
  2. Syntax for fgets():
  1. Syntax for puts():

Passing strings to functions

As strings are simply character arrays, we can pass strings to function in the same way we pass an array to a function, either as an array or as a pointer. Let's understand this with the following program:

Output:

As we can see, both of them yield the same Output.

Highlights:

  1. String can be passed to functions as a character array or even in the form of a pointer.

Strings and Pointers

As we have seen, strings in C are represented by character arrays which act as pointers. Hence, we can use pointers to manipulate or even perform operations on the string.

Output:

using pointers to manipulate or perform operations on a string

Note: Since character arrays act like pointers, we can easily use pointers to manipulate strings.

String Example in C

Here is a program that demonstrates everything we have learned in this article:

Output:

You can run and check your code in this Online C Compiler.

Difference between character Array and String literal

Before actually jumping to the difference, let us first recap string literals. A string literal is a sequence of zero or more multibyte characters enclosed in double quotes, as in "xyz". String literals are not modifiable (and are placed in read-only memory). An attempt to alter their values results in undefined behavior.

String literals can be used to initialize arrays. We have seen multiple examples of this throughout the article. Now, let us see the differences using the following examples:

This statement creates a character array that has been assigned a string literal. It behaves as a usual array with which we can perform regular operations, including modification. The only thing to remember is that although we have initialized 7 elements, its size is 8, as the compiler adds the \0 at the end.

The above statement creates a pointer that points to the string literal, i.e. to the first character of the string literal. Since we now know that string literals are stored in a read-only memory location, thus alteration is not allowed.

Note - While printing string literals, it is defined to declare them as constants like:

This prevents the warning we get while using printf() with string literals.

Highlights:

  1. String literals are stored on the read-only memory part of most compilers. Hence they cannot be modified.
  2. With character arrays, we can perform the usual operations on arrays including modification.
  3. Pointers that point to the string literal cannot be modified, just like string literals.

Conclusion

  • Strings in C are declared with character arrays, a linear sequence of characters.
  • The compiler automatically appends the Null character (\0) at the end of character arrays.
  • There are four ways of initializing a string.
  • Strings in C do not support the assignment operation once declared.
  • Strings in C can be read using scanf(); however, it only reads until it encounters whitespace.
  • The combination of fgets() and puts() tacked the problem of reading a line of text with spaces.
  • A string can be passed to a function as a character array or in the form of a pointer.
  • Since character arrays act like pointers, we can easily use pointers to manipulate strings.
  • We can modify character arrays; however, it is impossible to do so with pointers pointing to string literals.