C Programming: Working with Arrays of Characters 🎯

beginner
9 min

C Programming: Working with Arrays of Characters 🎯

Welcome to our C Programming tutorial on Arrays of Characters! In this lesson, you'll learn how to create and manipulate character arrays in C, a fundamental concept for any C programmer. Let's dive in! 💡

What are Character Arrays? 📝

In C, an array of characters is a collection of identically-typed elements, where each element is a single character. Just like other arrays, we can store character arrays in variables, and manipulate them using indexing.

Declaring Character Arrays 📝

To declare a character array, we use the following syntax:

c
char arrayName[arraySize];

For example:

c
char myName[20];

This declares a character array myName with a maximum size of 20 characters.

Initializing Character Arrays 📝

By default, C initializes all elements of an array to 0. However, when initializing a character array, we can provide initial values for each element.

c
char myName[20] = {"Hello, World!"};

This initializes the myName array with the string "Hello, World!".

Accessing Elements in Character Arrays 📝

To access elements in a character array, we use indexing, just like other arrays. The index starts at 0, and the last index is arraySize - 1.

c
#include <stdio.h> int main() { char myName[20] = {"Hello, World!"}; printf("%c\n", myName[0]); // Output: H printf("%c\n", myName[9]); // Output: , return 0; }

Common Character Array Functions 📝

C provides several functions to work with character arrays:

  1. strlen(char* str): Returns the length of a string (array of characters).
  2. strcpy(char* dest, const char* src): Copies the string from src to dest.
  3. strcmp(const char* str1, const char* str2): Compares two strings and returns 0 if they are equal, a positive or negative value based on the lexicographical order.

Example: Simple Character Array Program 💡

c
#include <stdio.h> #include <string.h> int main() { char name[20]; printf("Enter your name: "); fgets(name, sizeof(name), stdin); int length = strlen(name); printf("Your name is: "); for (int i = 0; i < length; ++i) { printf("%c", name[i]); } char reversedName[20]; for (int i = length - 1, j = 0; i >= 0; --i, ++j) { reversedName[j] = name[i]; } printf("\nReversed name: "); for (int i = 0; i < length; ++i) { printf("%c", reversedName[i]); } return 0; }

This program takes the user's input, prints it, and reverses it.

Quiz 📝

Quick Quiz
Question 1 of 1

What does the `strlen(char* str)` function do?


With this lesson, you've learned the basics of working with character arrays in C. You now know how to declare, initialize, and access elements in character arrays, as well as some common functions for handling character arrays.

Remember to practice and experiment with character arrays to solidify your understanding. In the next lesson, we'll explore C strings in more detail. Happy coding! 💡