Working with Character Arrays in C


Introduction

Character arrays in C are fundamental data structures used for storing sequences of characters, often referred to as strings. Understanding how to work with character arrays is crucial for tasks like text manipulation, input/output, and more. In this guide, we'll explore character arrays in C, their characteristics, and provide sample code to illustrate their usage.


Character Arrays vs. Strings

In C, character arrays are used to represent strings. A character array is a collection of characters terminated by a null character

'\0'
. The null character marks the end of the string. Here's an example:

char myString[] = "Hello, C!";

Character Array Operations

Character arrays in C can be manipulated using various functions from the standard library, which are defined in

<string.h>
. These functions include:

  • strlen()
    : Calculate the length of a string.
  • strcpy()
    : Copy one string to another.
  • strcat()
    : Concatenate two strings.
  • strcmp()
    : Compare two strings.

Sample Code

Let's explore some examples of working with character arrays in C:


Calculating String Length

#include <stdio.h>
#include <string.h>
int main() {
char myString[] = "Hello, C!";
int length = strlen(myString);
printf("Length of the string: %d\\n", length);
return 0;
}

Copying and Concatenating Character Arrays

#include <stdio.h>
#include <string.h>
int main() {
char source[] = "Hello, ";
char destination[20];
strcpy(destination, source); // Copy source to destination
strcat(destination, "World!"); // Concatenate "World!" to destination
printf("Combined string: %s\\n", destination);
return 0;
}

Comparing Character Arrays

#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "apple";
char str2[] = "banana";
int result = strcmp(str1, str2);
if (result == 0) {
printf("Strings are equal.\\n");
} else {
printf("Strings are not equal.\\n");
}
return 0;
}

Conclusion

Character arrays are a fundamental data type in C programming, used for representing strings. They are essential for text manipulation and various data processing tasks. This guide has provided an introduction to character arrays in C, covering their representation, key functions, and sample code to illustrate their usage. As you continue your journey in C programming, character arrays will be a valuable tool for working with text and character data.