0
0
Cprogramming~5 mins

Character arrays

Choose your learning style9 modes available
Introduction

Character arrays let you store and work with text in C. They hold letters, words, or sentences as a list of characters.

When you want to store a word or sentence in your program.
When you need to read text input from the user.
When you want to change or check individual letters in a word.
When you want to print text stored in your program.
When you want to compare two pieces of text.
Syntax
C
char array_name[size];

// Example:
char greeting[6];

The size is how many characters the array can hold.

Remember to leave space for the special '\0' character that marks the end of the text.

Examples
This array can hold a 4-letter word like "code" plus the end marker.
C
char word[5];
// Can hold 4 letters plus '\0' to end the string
The size is set automatically when you initialize with text.
C
char name[] = "Anna";
// Size is 5 automatically (4 letters + '\0')
This creates an empty string with space for 9 characters plus '\0'.
C
char empty[10] = {0};
// All characters start as '\0' (empty string)
Even one letter needs space for '\0' to mark the end.
C
char single_letter[2] = {'A', '\0'};
// Holds one letter and the end marker
Sample Program

This program creates a character array holding "Hello". It prints it, changes the first letter to 'J', then prints again.

C
#include <stdio.h>

int main() {
    char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
    
    printf("Before change: %s\n", greeting);

    // Change 'H' to 'J'
    greeting[0] = 'J';

    printf("After change: %s\n", greeting);

    return 0;
}
OutputSuccess
Important Notes

Character arrays end with a special '\0' character to mark the end of the text.

Always leave space for '\0' when declaring the array size.

Time complexity to access or change a character is O(1) because you use the index directly.

Common mistake: forgetting the '\0' causes unexpected behavior when printing or using string functions.

Use character arrays when you need to work with text at a low level in C.

Summary

Character arrays store text as a list of characters ending with '\0'.

You can change letters by accessing array positions.

Always remember to include space for the '\0' end marker.