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! 💡
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.
To declare a character array, we use the following syntax:
char arrayName[arraySize];For example:
char myName[20];This declares a character array myName with a maximum size of 20 characters.
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.
char myName[20] = {"Hello, World!"};This initializes the myName array with the string "Hello, World!".
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.
#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;
}C provides several functions to work with character arrays:
strlen(char* str): Returns the length of a string (array of characters).strcpy(char* dest, const char* src): Copies the string from src to dest.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.#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.
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! 💡