Back to C Programming
2026-03-267 min read

12.7 String Constants

Learn 12.7 String Constants step by step with clear examples and exercises.

Why This Matters

String constants play a vital role in C programming as they enable the storage, manipulation, and processing of textual data. They are essential for creating user interfaces, parsing input, and performing various string operations. Understanding string constants is crucial to writing efficient and effective programs, debugging real-world issues, and preparing for coding interviews.

Prerequisites

Before delving into string constants, it's essential to have a solid understanding of:

  1. C basics: variables, data types, operators, control structures, functions, and arrays.
  2. File handling: understanding how to read and write files in C.
  3. Basic memory management concepts: pointers and dynamic memory allocation.
  4. Understanding the difference between char arrays and string variables.
  5. Familiarity with various C Standard Library functions like printf(), scanf(), malloc(), and free().

Core Concept

Definition and Declaration

A string constant is a sequence of characters enclosed within double quotes ("). To declare a string variable, you need to allocate memory for it using an array of characters with the char data type. Here's an example:

char str[10] = "Hello, World!";

In this example, we have created a string variable named str with a maximum capacity of 9 characters (including the null terminator). The string "Hello, World!" is assigned to the array.

String Length and Accessing Characters

To determine the length of a string, you can use the strlen() function provided by the C Standard Library. To access individual characters in a string, you can use indexing:

#include <stdio.h>
#include <string.h>

int main() {
char str[10] = "Hello, World!";
int len = strlen(str);

printf("Length of the string: %d\n", len);
printf("First character: %c\n", str[0]);
printf("Last character: %c\n", str[len - 1]);

return 0;
}

String Concatenation and Comparison

To concatenate two strings, you can use the strcat() function. To compare two strings for equality, you can use the strcmp() function:

#include <stdio.h>
#include <string.h>

int main() {
char str1[20] = "Hello";
char str2[20] = "World";
char str3[40];

strcat(str1, " ");
strcat(str1, str2);

if (strcmp(str1, str2) == 0) {
printf("Strings are equal.\n");
} else {
printf("Strings are not equal.\n");
}

strcpy(str3, str1);
printf("Concatenated string: %s\n", str3);

return 0;
}

String Literals and Memory Allocation

String literals (e.g., "Hello, World!") are stored in read-only memory by the compiler. When you declare a string variable and assign it a string literal, the compiler automatically allocates memory for the string and initializes it with the provided value. However, be aware that modifying a string variable assigned a string literal will result in undefined behavior:

char str[10] = "Hello, World!";
str[0] = 'H'; // Undefined behavior due to modifying a string literal

String Pointers and Arrays

When you pass a string as an argument to a function, it is passed as a pointer to the first character of the string. This allows functions to manipulate strings without knowing their exact length:

void reverse_string(char *str) {
int len = strlen(str);
char temp;

for (int i = 0; i < len / 2; ++i) {
temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
}
}

#include <stdio.h>
#include <string.h>

int main() {
char str[20] = "Hello, World!";

reverse_string(str);
printf("Reversed string: %s\n", str);

return 0;
}

String Manipulation Functions

The C Standard Library provides various functions for manipulating strings, such as strcpy(), strcat(), strcmp(), strlen(), and memchr(). These functions are essential for performing common string operations like copying, concatenating, comparing, finding specific characters, and more.

Worked Example

Let's create a simple program that reads a line of text from the user, reverses it, and then writes the reversed text back to the console.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void reverse_string(char *str) {
int len = strlen(str);
char temp;

for (int i = 0; i < len / 2; ++i) {
temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
}
}

int main() {
char *line = NULL;
size_t len = 0;
ssize_t read;

printf("Enter a line of text: ");
getline(&line, &len, stdin);

reverse_string(line);
printf("Reversed line: %s\n", line);

free(line);
return 0;
}

Common Mistakes

  1. Forgetting to include the required header files. Remember to include `, `, and any other necessary headers for your program.
  2. Modifying string literals. String literals are stored in read-only memory, so modifying them will result in undefined behavior. Instead, use string variables or dynamic memory allocation to store modifiable strings.
  3. Not considering the null terminator when accessing or manipulating strings. Always remember that strings are null-terminated arrays of characters, and you should account for the null terminator when working with them.
  4. Ignoring string function return values. Functions like strlen(), strcat(), and strcmp() return important information (e.g., string length or comparison result), so make sure to use these return values in your code.
  5. Not handling dynamic memory allocation errors. When using dynamic memory allocation, always check for errors and handle them appropriately to prevent memory leaks and program crashes.
  6. Using single quotes instead of double quotes for string constants. Single quotes are reserved for character constants, while double quotes are used for string constants.
  7. Not properly terminating strings when using dynamic memory allocation. When allocating memory dynamically for a string, don't forget to add space for the null terminator (\0) at the end of the string.
  8. Misunderstanding the difference between char arrays and string variables. A char array is an array of characters, while a string variable is a char array with a null terminator at the end (indicating the end of the string).
  9. Not considering the impact of string manipulation functions on memory. String manipulation functions like strcpy() and strcat() require additional memory to accommodate the resulting strings, so be mindful of your program's memory usage.

Practice Questions

  1. Write a function that finds the longest common substring between two strings.
  2. Implement a function that checks if a given string is a palindrome (reads the same forward and backward).
  3. Create a simple calculator that accepts user input for mathematical expressions involving operators (+, -, *, /) and parentheses.
  4. Write a program that counts the number of occurrences of each character in a given string.
  5. Implement a function that sorts an array of strings lexicographically.
  6. Write a function that checks if a given string is a valid email address.
  7. Create a program that reads a file line by line and performs operations on each line (e.g., word count, character count).
  8. Implement a function that replaces all occurrences of a specific substring in a given string.
  9. Write a program that generates all permutations of a given string.
  10. Create a function that compresses a string by replacing consecutive identical characters with their counts (e.g., "aaabbbccc" becomes "3a2b3c").

FAQ

  1. Why do we use double quotes for string constants instead of single quotes? Double quotes are used to define string constants because they allow for embedded escape sequences (e.g., \n for newline). Single quotes are reserved for character constants.
  2. What happens when we try to modify a string literal in C? Modifying a string literal results in undefined behavior, as it is stored in read-only memory by the compiler.
  3. How does the C Standard Library handle string manipulation functions like strcat() and strlen()? The C Standard Library uses pointers to traverse strings, which makes these functions efficient for handling string operations.
  4. What is the difference between a char array and a string variable in C? A char array is an array of characters, while a string variable is a char array with a null terminator at the end (indicating the end of the string).
  5. Why do we need to include for string manipulation functions like strcat() and strlen() in C? The ` header file contains function declarations for various string manipulation functions, such as strcat(), strlen()`, and others. Including this header ensures that the functions are properly defined and can be used in your program.
  6. Why does the C Standard Library use pointers to handle strings? Using pointers allows the C Standard Library to efficiently manipulate strings without having to know their exact length, as well as providing a consistent interface for various string operations.
  7. What is the purpose of the null terminator in a string variable? The null terminator (\0) marks the end of a string variable and allows C programs to easily identify the end of the string when traversing or manipulating it.
  8. Why can't we modify a string literal in C? String literals are stored in read-only memory by the compiler, so modifying them will result in undefined behavior. Instead, you should use string variables or dynamic memory allocation to store modifiable strings.
  9. What is the difference between strcpy() and strncpy() in C? strcpy() copies a source string into a destination array until it reaches the null terminator, while strncpy() copies a specified number of characters from the source string to the destination array, regardless of the null terminator.
  10. What is the difference between strcat() and strncat() in C? strcat() appends a source string to a destination array until it reaches the null terminator, while strncat() appends a specified number of characters from the source string to the destination array, regardless of the null terminator.