CS Engineering Gyan

Strings in C

Almost every program eventually needs to work with text, whether that means displaying a channel name, validating a username, or comparing two words entered by a user. Many modern languages provide a dedicated string data type that handles all of this automatically behind the scenes. C takes a different approach, one that is closer to the underlying hardware and, once understood, gives you a much deeper appreciation for how text is actually represented in memory.

In C, a string is not a separate data type at all. Instead, it is simply an array of characters that ends with a special marker known as the null character. This design choice explains many of the quirks beginners encounter when first working with strings in C, and understanding it thoroughly will make string-related bugs far easier to diagnose later.

In this tutorial, you will learn how strings are represented internally in C, how to declare and initialize them, how to read and display string input, and how to use some of the most commonly used string handling functions, including those for measuring length, copying, concatenating, and comparing strings.


What is a String in C?

A string in C is a sequence of characters stored in a character array, terminated by a special null character represented as \0. This null character marks the end of the actual text, allowing functions that work with strings to know exactly where the meaningful data stops, even if the array itself was declared with extra unused space.

Example

#include <stdio.h>

int main() {

    char channelName[20] = "CS Engineering Gyan";

    printf("Channel name: %s", channelName);

    return 0;

}

Output

Channel name: CS Engineering Gyan

Even though the array was declared with room for twenty characters, the actual text stored is shorter, and the null character automatically added at the end tells functions like printf exactly where to stop reading.


Declaring and Initializing Strings

There are a few different ways to declare and initialize a string in C, and understanding each approach helps clarify what is actually happening in memory behind the scenes.

Method Example
String literal initialization char greeting[10] = "Hello";
Character-by-character initialization char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
Without specifying a size char greeting[] = "Hello";

When a string is declared without an explicit size but initialized directly with text, the compiler automatically calculates the required size, including one extra position reserved specifically for the null character.


Reading Strings Using scanf

As covered briefly in the input and output tutorial, scanf can be used to read a string typed in by the user, though it comes with an important limitation that becomes especially relevant when working extensively with text.

Example

#include <stdio.h>

int main() {

    char username[20];

    printf("Enter a username: ");

    scanf("%s", username);

    printf("Username entered: %s", username);

    return 0;

}

Output

Enter a username: CSGyanUser

Username entered: CSGyanUser

The %s specifier used with scanf automatically stops reading input at the first whitespace character it encounters, which means it cannot be used to read a full sentence containing multiple words separated by spaces.


Reading Full Lines with fgets

When a program needs to accept input that includes spaces, such as a full name or a sentence, the fgets function provides a more suitable alternative to scanf, since it reads an entire line of text at once, including any spaces it contains.

Example

#include <stdio.h>

int main() {

    char fullName[30];

    printf("Enter your full name: ");

    fgets(fullName, 30, stdin);

    printf("Hello, %s", fullName);

    return 0;

}

Output

Enter your full name: Kailash Joshi

Hello, Kailash Joshi

The second argument passed to fgets specifies the maximum number of characters to read, which helps prevent the function from writing beyond the boundaries of the array reserved for the string.


Finding the Length of a String

The strlen function calculates the number of characters in a string, not counting the null character that marks its end. This function is part of the string handling library, which needs to be included before it can be used.

Example

#include <stdio.h>

#include <string.h>

int main() {

    char channel[] = "CS Engineering Gyan";

    int length = strlen(channel);

    printf("Length of channel name: %d", length);

    return 0;

}

Output

Length of channel name: 20

Copying Strings with strcpy

Unlike numeric variables, strings in C cannot be copied simply by using the assignment operator between two character arrays. Instead, the strcpy function is used to copy the contents of one string into another.

Example

#include <stdio.h>

#include <string.h>

int main() {

    char source[] = "CS Engineering Gyan";

    char destination[30];

    strcpy(destination, source);

    printf("Copied string: %s", destination);

    return 0;

}

Output

Copied string: CS Engineering Gyan

It is important that the destination array is large enough to hold the entire source string, including its null character, since strcpy does not automatically check for available space.


Joining Strings with strcat

The strcat function appends the contents of one string onto the end of another, effectively joining two strings together into a single combined result stored in the first string.

Example

#include <stdio.h>

#include <string.h>

int main() {

    char greeting[30] = "Welcome to ";

    char channel[] = "CS Engineering Gyan";

    strcat(greeting, channel);

    printf("%s", greeting);

    return 0;

}

Output

Welcome to CS Engineering Gyan

As with strcpy, the array receiving the combined result must have enough allocated space to hold both original strings together, or the program risks writing beyond the array's boundaries.


Comparing Strings with strcmp

Since strings cannot be compared directly using relational operators like == in C, the strcmp function is used instead, comparing two strings character by character and returning a value that indicates their relationship.

Return Value Meaning
0 The two strings are exactly equal.
Less than 0 The first string is alphabetically earlier than the second string.
Greater than 0 The first string is alphabetically later than the second string.

Example

#include <stdio.h>

#include <string.h>

int main() {

    char enteredPassword[] = "csgyan123";

    char correctPassword[] = "csgyan123";

    if (strcmp(enteredPassword, correctPassword) == 0) {

        printf("Password matched.");

    } else {

        printf("Password did not match.");

    }

    return 0;

}

Output

Password matched.

Converting Case in Strings

While C does not provide a single built-in function to convert an entire string to uppercase or lowercase, this can be achieved by looping through each character individually and applying a conversion function from the character handling library.

Example

#include <stdio.h>

#include <ctype.h>

#include <string.h>

int main() {

    char text[] = "cs engineering gyan";

    int i;

    for (i = 0; i < strlen(text); i++) {

        text[i] = toupper(text[i]);

    }

    printf("%s", text);

    return 0;

}

Output

CS ENGINEERING GYAN

Here, the toupper function is applied individually to each character within the loop, gradually converting the entire string to uppercase one character at a time.


Strings as Character Arrays

Concept Explanation
Underlying Structure A string is fundamentally a character array, meaning individual characters can be accessed directly using array indexing.
Null Character The null character marks the logical end of the string, even if the array itself has additional unused space beyond it.
Fixed Size Like other arrays, a string declared with a fixed size cannot grow beyond that size once it has been created.

Example

#include <stdio.h>

int main() {

    char channel[] = "CSGyan";

    printf("First character: %c", channel[0]);

    return 0;

}

Output

First character: C

Best Practices When Working with Strings


Common Mistakes Beginners Make

Mistake Correct Practice
Using == to compare two strings. Use the strcmp function to properly compare the contents of two strings.
Forgetting to include string.h before using string functions. Always include the string.h header when using functions such as strlen, strcpy, or strcat.
Declaring a character array too small for the text it needs to hold. Reserve extra space in the array to account for the null character and any planned concatenation.
Expecting scanf with %s to read text containing spaces. Use fgets instead of scanf when the input may include multiple words separated by spaces.

Frequently Asked Interview Questions

  1. What is a string in C?
    A string in C is a sequence of characters stored in a character array, terminated by a special null character.
  2. What is the purpose of the null character in a string?
    The null character marks the logical end of a string's actual content, allowing functions to know where meaningful text stops within the array.
  3. Why can't two strings be compared directly using the == operator in C?
    The == operator would compare memory addresses rather than the actual character content, so the strcmp function must be used instead to compare string contents.
  4. What does the strlen function do?
    The strlen function returns the number of characters in a string, not including the terminating null character.
  5. What is the purpose of the strcpy function?
    The strcpy function copies the contents of one string into another character array.
  6. What does the strcat function do?
    The strcat function appends the contents of one string onto the end of another string.
  7. What return values does strcmp produce, and what do they mean?
    strcmp returns zero when the strings are equal, a negative value when the first string is alphabetically earlier, and a positive value when the first string is alphabetically later.
  8. Why does %s in scanf fail to read a full sentence with spaces?
    The %s specifier automatically stops reading input at the first whitespace character it encounters, making it unsuitable for input containing multiple words.
  9. Why is fgets often preferred over scanf for reading strings?
    fgets can read an entire line of text, including spaces, while scanf with %s stops at the first space it encounters.
  10. Can individual characters within a string be accessed directly?
    Yes, since a string is fundamentally a character array, individual characters can be accessed directly using standard array indexing.
  11. What header file must be included to use common string handling functions in C?
    The string.h header must be included to use functions such as strlen, strcpy, strcat, and strcmp.
  12. What could go wrong if the destination array in strcpy is too small?
    Writing beyond the allocated size of the destination array can corrupt nearby memory, leading to unpredictable program behavior.

Summary

Strings in C are built on top of a concept you already understand from earlier tutorials, character arrays, combined with a special null character marking where meaningful text ends. Because C does not provide a dedicated string type with built-in operators, working with text requires using dedicated library functions such as strlen, strcpy, strcat, and strcmp for tasks that might feel automatic in other languages.

In this tutorial, you learned how strings are represented internally, different ways to declare and initialize them, how to read string input using both scanf and fgets, and how to use the most common string handling functions to measure, copy, join, and compare text. With this understanding in place, you are ready to move on to functions and recursion, where you will learn how to organize C code into clean, reusable blocks of logic.


← Previous: Arrays in C Next: Functions & Recursion →

Home Visit Our YouTube Channel