Table of contents
1.
Introduction
2.
Syntax
3.
Example
3.1.
C
4.
Initialization of Character Array in C
4.1.
Direct Initialization at Declaration:
4.2.
Initialization Using strcpy:
4.3.
Partial Initialization
5.
Examples of Character Array in C
5.1.
Example 1: Reading and Printing a String
5.2.
C
5.3.
Example 2: Concatenating Two Strings
5.4.
C
5.5.
Example 3: Comparing Two Strings
5.6.
C
6.
What is the Use of Char Array in C?
6.1.
Storing Strings
6.2.
Input/Output Operations
6.3.
Data Processing
6.4.
Interfacing with Hardware
6.5.
Network Communication
6.6.
Buffering Data
7.
Importance of Char Array
7.1.
Flexibility in Memory Usage
7.2.
Efficiency in Processing
7.3.
Compatibility with C Standard Library
7.4.
Foundation for Advanced Features
7.5.
Cross-Language Integration
8.
Program for Char Array in C
8.1.
Program Overview
8.2.
Complete Program Code
8.3.
C
8.4.
Explanation of the Program
9.
Similarities & Differences between Character Array and Character Pointer in C
9.1.
Similarities
9.2.
Differences
9.2.1.
Memory Allocation
9.2.2.
Modifiability:
9.2.3.
Memory Management:
9.2.4.
Use Cases
10.
Difference Between Character Array and String
10.1.
Key Points to remember 
11.
Frequently Asked Questions
11.1.
Can I change the size of a character array after it is declared?
11.2.
How do I safely copy a string into a character array?
11.3.
What is the purpose of the null terminator in strings?
12.
Conclusion
Last Updated: Dec 20, 2024
Easy

Character Array in C

Author Riya Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Character arrays are an important concept in the C programming language. They allow you to store & manipulate sequences of characters, which are fundamental in many programming tasks. 

Character Array in C

In this article, we will learn the basics of character arrays in C, including their syntax, initialization, & usage. We will also discuss the differences between character arrays & character pointers. 

Syntax

In C programming, defining a character array follows a straightforward syntax that is easy to understand & apply. To declare a character array, you specify the type of the array as char, followed by the array name & the size of the array enclosed in square brackets. Here's the basic syntax:

char arrayName[arraySize];


For example, if you want to create a character array named greeting that can hold up to 10 characters, you would write:

char greeting[10];


This line of code sets aside a block of memory to hold 10 characters. When initializing character arrays, you can directly assign a string to them at the time of declaration, which fills the array with the corresponding characters including a null terminator '\0' that indicates the end of the string. Here’s how you can initialize the greeting array:

char greeting[10] = "Hello";


In this case, greeting will contain the characters H, e, l, l, o, and '\0', with the rest of the spaces in the array remaining unused. It's crucial to ensure the size of the array is sufficient to include the null character; otherwise, it can lead to errors in your program.

Example

Suppose you need to create a program that stores and prints a greeting message. Here’s how you can do it using a character array:

  • C

C

#include <stdio.h>

int main() {

   char greeting[20] = "Hello, world!";

   printf("%s\n", greeting);

   return 0;

}
You can also try this code with Online C Compiler
Run Code

Output

Hello, world!

 

In this example:

  1. Array Declaration & Initialization: The character array greeting is declared with enough space to hold up to 19 characters plus the null terminator. It is immediately initialized with the string "Hello, world!".
     
  2. Using printf to Display the Array: The printf function is used to print the string stored in the array. The %s format specifier in printf tells C to expect a string (a sequence of characters ending with a null character).

Initialization of Character Array in C

Initializing character arrays in C is a straightforward task but essential for ensuring your arrays function as expected in your programs. Here, we'll discuss how to initialize character arrays properly using both direct assignment at declaration and runtime assignment.

Direct Initialization at Declaration:

When you declare a character array, you can immediately initialize it with a specific string. 

Here’s how it is typically done:

char name[50] = "Rahul Singh";


In this example, name is a character array that can hold up to 49 characters plus a null terminator. The array is initialized with the string "Rahul Singh" followed by a null character automatically added by the compiler.

Initialization Using strcpy:

If you need to initialize an array after declaration, you can use the strcpy function from the C standard library. This method is useful when the initial value is not known at the time of declaration:

#include <string.h>
char name[50];
strcpy(name, "Sinki Kumari");


Here, strcpy is used to copy the string "Sinki Kumari" into the array name, including the null terminator. It’s important to ensure that the array has enough space to store the entire string and the null terminator to avoid buffer overflows.

Partial Initialization

You can also partially initialize character arrays. If you initialize an array with fewer characters than its declared size, the rest of the array will automatically be filled with null characters:

char buffer[10] = "Hi";


This will result in buffer containing "Hi" followed by eight null characters. This feature is particularly useful for ensuring that unused parts of the array do not contain garbage values, which can lead to unpredictable program behavior.

Examples of Character Array in C

To understand the concept better, we will look at few examples which will clear every doubt you may have : 

Example 1: Reading and Printing a String

This example demonstrates how to read a string from the user and then print it using a character array:

  • C

C

#include <stdio.h>

int main() {

   char input[100];

   printf("Enter a string: ");

   fgets(input, sizeof(input), stdin);  // Read string from user input

   printf("You entered: %s", input);

   return 0;

}
You can also try this code with Online C Compiler
Run Code

Output

Enter a string: Hello
You entered: Hello


In this code:

  • input is a character array that can hold up to 99 characters plus a null terminator.
     
  • fgets is used for reading a string from the standard input, which safely copies the string to the array input and ensures that no overflow occurs.
     
  • The string entered by the user is then printed to the console.

Example 2: Concatenating Two Strings

Here’s how you can concatenate two strings using character arrays:

  • C

C

#include <stdio.h>

#include <string.h>

int main() {

   char first[20] = "Hello, ";

   char second[] = "World!";

   strcat(first, second);  // Append 'second' to 'first'

   printf("Result: %s\n", first);

   return 0;

}
You can also try this code with Online C Compiler
Run Code

Output

Result: Hello, World!
  • first is initialized with "Hello, " and has enough space to hold additional characters.
     
  • strcat is used to append the string in second to first, resulting in first containing "Hello, World!".
     
  • This shows how strings can be combined using basic string manipulation functions in C.

Example 3: Comparing Two Strings

Comparing two strings to see if they are the same can be done using the strcmp function:

  • C

C

#include <stdio.h>

#include <string.h>

int main() {

   char str1[10] = "apple";

   char str2[10] = "orange";

   if(strcmp(str1, str2) == 0) {

       printf("The strings are identical.\n");

   } else {

       printf("The strings are different.\n");

   }

   return 0;

}
You can also try this code with Online C Compiler
Run Code

Output

The strings are different.
  • strcmp compares str1 and str2. If they are the same, it returns 0; otherwise, it returns a non-zero value indicating they are different.
     
  • This example effectively demonstrates the use of strcmp for string comparison.

What is the Use of Char Array in C?

Character arrays in C are incredibly versatile and play a crucial role in various programming tasks. Here, we'll discuss few important key uses of character arrays that demonstrate their importance in C programming.

Storing Strings

The primary use of character arrays is to store strings. In C, strings are arrays of characters terminated by a null character ('\0'). This makes character arrays ideal for holding text data that needs to be processed or manipulated within a program.

Input/Output Operations

Character arrays are essential for input/output operations in C. They are used to gather input from users, read data from files, and display messages to the screen. Functions like scanf, fgets, and printf utilize character arrays to handle text data efficiently.

Data Processing

Character arrays facilitate the processing of text data. This includes tasks such as parsing text files, processing user commands, or any scenario where text manipulation is required. Functions like strcat, strcpy, strlen, and strcmp provide powerful tools for working with text stored in character arrays.

Interfacing with Hardware

In systems programming, character arrays are used to interface with hardware components that require data in the form of strings. For example, sending commands to a printer or interacting with embedded systems often involves character arrays to format and transmit commands.

Network Communication

In network programming, character arrays are used to construct and parse messages that are sent over networks. Whether it’s HTTP requests or responses, FTP commands, or any other protocol, character arrays are fundamental for encapsulating and decoding message data.

Buffering Data

Character arrays serve as buffers in many applications, holding data temporarily while it is being transferred from one part of a program to another, or between programs and hardware. This buffering is critical for performance optimization in data-intensive applications.

Importance of Char Array

Character arrays hold significant importance in C programming for several reasons. Let’s look at few of them : 

Flexibility in Memory Usage

Character arrays provide a flexible way to manage memory for storing strings. Unlike some other high-level languages that offer dynamic string types, C relies on character arrays for explicit control over how much memory is allocated for storing text. This is particularly useful in environments where memory is limited or when precise control over resource use is necessary.

Efficiency in Processing

Using character arrays can lead to more efficient programs. Because they allow direct access to each character in a string, operations like searching, sorting, and editing text can be performed quickly and with minimal overhead. This direct access is a boon for performance-critical applications such as real-time systems or large-scale data processing tasks.

Compatibility with C Standard Library

The C standard library provides a plethora of functions designed to work with character arrays, such as strcpy, strcat, strlen, and strncmp. These functions are optimized for performance and are thoroughly tested, making them reliable tools for developing robust applications.

Foundation for Advanced Features

Character arrays serve as the foundation for more complex data types and structures. For example, understanding character arrays is essential when working with more advanced features in C like pointers, structures, and even interfacing with operating systems. They are also crucial for handling file I/O operations, where data is frequently read from or written to files as arrays of characters.

Cross-Language Integration

Character arrays play a vital role in integrating C programs with other languages. They provide a straightforward mechanism for data interchange, particularly for languages that do not natively support complex string types or where inter-language operability is required. This makes C and its character arrays valuable in diverse development environments.

Program for Char Array in C

This program will demonstrate how to create, manipulate, and use character arrays in a simple user interaction scenario.

Program Overview

The program will perform the following tasks:

  1. Declare a character array.
     
  2. Allow the user to input a string.
     
  3. Display the string back to the user.
     
  4. Count the number of characters in the string.
     
  5. Reverse the string and display it.

Complete Program Code

  • C

C

#include <stdio.h>

#include <string.h>

int main() {

   char text[100];  // Declare a character array of size 100

   printf("Enter a string (up to 99 characters): ");

   fgets(text, sizeof(text), stdin);  // Read a line of text from standard input

   // Display the input text

   printf("You entered: %s", text);

   // Count the number of characters in the string

   int length = strlen(text) - 1;  // Subtract 1 to ignore the newline character

   printf("Number of characters: %d\n", length);

   // Reverse the string

   char reversed[100];

   for(int i = 0; i < length; i++) {

       reversed[i] = text[length - 1 - i];

   }

   reversed[length] = '\0';  // Null-terminate the reversed string

   // Display the reversed string

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

   return 0;

}
You can also try this code with Online C Compiler
Run Code

Output

Enter a string (up to 99 characters): Hello World
You entered: Hello World
Number of characters: 11
Reversed string: dlroW olleH

Explanation of the Program

  1. Character Array Declaration: The text array is declared with enough space to hold up to 99 characters plus a null terminator.
     
  2. Input Handling: The program uses fgets to safely read a string from the user, ensuring that no more than 99 characters are read to prevent buffer overflow.
     
  3. String Display and Length Calculation: The input string is displayed, and its length is calculated using strlen, accounting for the newline character typically included by fgets.
     
  4. String Reversal: A loop is used to reverse the string manually. The reversed string is stored in another character array reversed, ensuring it is null-terminated after the loop.

Similarities & Differences between Character Array and Character Pointer in C

Learning the similarities and differences between character arrays and character pointers in C is very important for understanding string manipulation and memory management in programming. 

Both are used extensively in C for handling text data, but they have distinct characteristics that affect their usage in different scenarios.

Similarities

  • String Handling: Both character arrays and character pointers can be used to handle strings. They can point to sequences of characters and can be used with standard string functions such as strcpy, strlen, and printf.
     
  • Accessing Characters: Individual characters in both character arrays and pointers can be accessed using indexing, e.g., array[3] or pointer[3].

Differences

Memory Allocation

  • Character Array: A character array allocates a fixed amount of memory during its declaration, e.g., char str[10]; allocates 10 bytes of memory.
     
  • Character Pointer: A character pointer needs to be assigned to an existing array or dynamically allocated memory, e.g., char *str = malloc(10);.

Modifiability:

  • Character Array: The base address of an array is fixed; the array itself cannot be re-pointed to another memory location, although the contents can be modified.
     
  • Character Pointer: A pointer can be modified to point to different memory addresses, which makes it more flexible but also prone to errors if not handled carefully.

Memory Management:

  • Character Array: Memory for character arrays is automatically managed if they are declared locally (i.e., on the stack). It is allocated and deallocated by the compiler.
     
  • Character Pointer: When using pointers with dynamically allocated memory (from the heap), you need to manually manage the memory by using malloc and free to prevent memory leaks.

Use Cases

  • Character Array: Best for situations where the size of the string is known at compile time and does not need resizing.
     
  • Character Pointer: More suitable for situations where the string size can vary, requiring dynamic memory allocation.

Difference Between Character Array and String

AspectCharacter ArrayString
DefinitionAn array of characters that can include any characters and does not have to be null-terminated.Typically refers to a null-terminated array of characters used to represent text data.
Declarationchar arr[10]; can be uninitialized or initialized with or without a null terminator.char str[] = "Hello"; must be null-terminated either explicitly or implicitly.
Memory AllocationFixed size specified at declaration; cannot be resized.Often uses character arrays but can be resized if dynamically managed via pointers.
UsageCan be used to store non-string data if the null terminator is not used.Used for storing human-readable text that ends with a null character ('\0').
FunctionsCan use all string functions if null-terminated, otherwise limited to certain manipulations.Can use all string-related functions from the C standard library (strcpy, strlen, etc.).
ModifiabilityThe contents can be changed, but the array size is fixed.Can change contents if space allows; if using a pointer, the memory can be reallocated to fit new content.
Examplechar data[5] = {'A', 'B', 'C'}; No null terminator, not a string.char text[] = "ABC"; Includes implicit null terminator, considered a string.

Key Points to remember 

  • Character Arrays are versatile and can be used for storing both string and non-string data, depending on whether they are null-terminated.
     
  • Strings in C are character arrays specifically used for textual data, and they must be null-terminated to function properly with string functions.

Frequently Asked Questions

Can I change the size of a character array after it is declared?

No, the size of a character array is fixed once it is declared. To work with variable-sized strings, you should use character pointers and dynamically allocate memory using functions like malloc and free.

How do I safely copy a string into a character array?

To safely copy a string into a character array, use the strcpy function from the C standard library, ensuring that the destination array is large enough to hold the source string and the null terminator. For even safer operations, consider strncpy which limits the number of characters copied.

What is the purpose of the null terminator in strings?

The null terminator ('\0') marks the end of a string in character arrays. This allows functions like printf and strlen to determine where the string ends, preventing them from reading beyond the allocated memory, which could lead to undefined behavior or program crashes.

Conclusion

In this article, we have learned about character arrays in C, their syntax, initialization, and practical usage examples. We discussed about their importance, how they differ from character pointers, and talked about common questions related to their use. Understanding these aspects of character arrays allows you to handle text data effectively in your C programs, ensuring that you manage memory efficiently and utilize the C standard library's functions to their fullest potential. 

Live masterclass