C

Character Arrays in C Programming

In C, a Character Array is a collection of variables of type char stored in contiguous memory locations. While a standard array might store a list of integers, a character array is primarily used to store and manipulate text.

When a character array is used to store a sequence of characters followed by a special "null" marker, it is referred to as a String.

1. The Theory: Memory and Storage

A character is stored in C as a 1-byte integer using its ASCII (American Standard Code for Information Interchange) value. For example, the character 'A' is stored as the value 65.

The Null Terminator (\0)

This is the most critical concept in character arrays.

  • To distinguish a "random list of characters" from a "proper string," C uses the null character \0.

  • The \0 has an ASCII value of 0.

  • It acts as a "sentinel" or a "stop sign," telling functions like printf() or strlen() where the text ends.

Crucial Rule: If you want to store a string of 5 characters (like "Hello"), your array must have a size of at least 6 to accommodate the hidden \0 at the end.

2. Declaration and Initialization

There are several ways to initialize a character array. The method you choose affects how the null terminator is handled.

A. Individual Element Initialization


char arr[5] = {'H', 'e', 'l', 'l', 'o'}; 
// This is a CHARACTER ARRAY, but NOT a string because it lacks '\0'.

B. String Literal Initialization


char str[6] = "Hello"; 
// The compiler automatically adds '\0' at the end. 
// Total size used: 6 bytes.

C. Implicit Sizing


char greeting[] = "Welcome"; 
// The compiler calculates the size as 8 (7 characters + 1 null terminator).

3. Reading and Writing Character Arrays

Handling text input is slightly different than handling numbers because of how whitespace is treated.

  • printf("%s", str): Prints characters until it hits the first \0.

  • scanf("%s", str): Reads a sequence of characters until it hits whitespace (space, tab, or newline). It automatically appends \0.

  • fgets(str, size, stdin): The preferred method for reading strings with spaces. It reads an entire line including spaces and stops at a newline or when the buffer is full.

4. Practical Code Example

This program demonstrates the difference between manual character assignment and string-style handling.


#include <stdio.h>

int main() {
    // Declaring a character array for a name
    char name[30];

    printf("Enter your full name: ");
    
    // Using fgets to allow spaces in the name
    fgets(name, sizeof(name), stdin);

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

    // Demonstrating manual character manipulation
    char code[] = {'C', 'p', 'r', 'o', 'g', '\0'};
    printf("Subject: %s\n", code);

    // Accessing individual characters
    printf("The first letter of the subject is: %c\n", code[0]);

    return 0;
}

5. Character Array vs. String Literal Pointer

It is important to understand the difference between these two declarations:

  1. char arr[] = "Hello";: This creates an array on the stack. You can modify its contents (e.g., arr[0] = 'M'; changes it to "Mello").

  2. char *ptr = "Hello";: This creates a pointer to a string literal stored in read-only memory. Trying to modify ptr[0] will result in a runtime crash (Segmentation Fault).

6. Key Takeaways and Best Practices

  • Always over-allocate: If you expect 50 characters of input, define the array as char str[51] or char str[60] to be safe from the null terminator requirement.

  • Avoid gets(): Never use the gets() function; it is deprecated and dangerous because it doesn't check array bounds, leading to security vulnerabilities. Use fgets() instead.

  • Manual Null Termination: If you are building a string character-by-character using a loop, you must manually add str[i] = '\0'; at the end to make it a valid string.

Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now