Character arrays in C++ are arrays used to store multiple characters together. They are commonly used to store words and sentences as strings.
What is a Character Array?
A character array is an array of characters (char) where each element stores a single character.
Character arrays are often used to represent strings in C++.
Why Use Character Arrays?
Character arrays are useful because they:
- Store text data
- Handle words and sentences
- Work efficiently with strings
- Are widely used in programming
Syntax of Character Array
char array_name[size];
Example of Declaration
char name[10];
This array can store up to 9 characters plus a null character (\0).
Initializing Character Array
char name[] = "Ali";
How Strings Work in Character Arrays
A string in C++ ends with a special null character:
\0
For example:
'A' 'l' 'i' '\0'
Example Program
#include <iostream>
using namespace std;
int main() {
char name[] = "Ahmed";
cout << name;
return 0;
}
Output
Ahmed
Accessing Individual Characters
Each character has an index number.
#include <iostream>
using namespace std;
int main() {
char name[] = "Ali";
cout << name[0] << endl;
cout << name[1] << endl;
cout << name[2] << endl;
return 0;
}
Output
A
l
i
Taking Input in Character Array
#include <iostream>
using namespace std;
int main() {
char name[20];
cin >> name;
cout << name;
return 0;
}
Using getline for Full Sentence
#include <iostream>
using namespace std;
int main() {
char sentence[50];
cin.getline(sentence, 50);
cout << sentence;
return 0;
}
Common Character Array Functions
Character arrays can work with functions from the <cstring> library.
Examples:
strlen()→ Find lengthstrcpy()→ Copy stringstrcat()→ Join stringsstrcmp()→ Compare strings
Example of strlen()
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char name[] = "Cplusplus";
cout << strlen(name);
return 0;
}
Advantages of Character Arrays
- Efficient memory usage
- Fast string processing
- Useful in low-level programming
- Compatible with C language functions
Disadvantages
- Fixed size
- Manual memory handling
- Less safe than modern string class
Why Character Arrays are Important
Character arrays are important because they:
- Form the base of string handling
- Are used in system programming
- Help understand memory concepts
- Are widely used in C and C++
Real-Life Example
Think of a word written letter by letter in separate boxes:
- Each box stores one character
- Together they form a complete word
This is how character arrays work.
Conclusion
Character arrays in C++ are essential for storing and managing text data. They provide a basic and efficient way to work with strings and are an important concept for understanding string manipulation and memory handling in programming.