Back to C++ Home

Arrays & Strings

Arrays and strings are fundamental data structures in C++ that allow you to store and manipulate collections of data. Understanding how to work with arrays and strings is essential for any C++ programmer, as they form the foundation for more complex data structures and algorithms. This comprehensive guide covers everything from basic array operations to advanced string manipulation techniques.

1. Understanding Arrays

An array is a collection of elements of the same data type stored in contiguous memory locations. Arrays provide an efficient way to store multiple values of the same type under a single variable name. Each element in an array can be accessed using an index, which starts from 0 in C++.

Arrays are particularly useful when you need to work with a fixed number of elements of the same type. For example, storing scores of 50 students, temperatures for 7 days of the week, or coordinates for a 3D point. The contiguous memory allocation makes arrays very efficient for iteration and random access operations.

One important characteristic of arrays in C++ is that their size must be known at compile time (for static arrays). This means you cannot resize an array after it's been declared. However, C++ also provides dynamic arrays and the Standard Template Library (STL) containers like vector for more flexible array-like structures.

Declaration and Initialization

#include <iostream>
using namespace std;

int main() {
    // Declaration
    int arr[5];
    
    // Initialization
    int arr1[5] = {1, 2, 3, 4, 5};
    int arr2[] = {10, 20, 30};  // Size determined automatically
    int arr3[5] = {1, 2};  // Remaining elements are 0
    
    // Accessing elements
    cout << arr1[0] << endl;  // First element
    cout << arr1[4] << endl;  // Last element
    
    return 0;
}

Array Operations

#include <iostream>
using namespace std;

int main() {
    int arr[5] = {10, 20, 30, 40, 50};
    
    // Traversing array
    for (int i = 0; i < 5; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
    
    // Finding sum
    int sum = 0;
    for (int i = 0; i < 5; i++) {
        sum += arr[i];
    }
    cout << "Sum: " << sum << endl;
    
    // Finding maximum
    int max = arr[0];
    for (int i = 1; i < 5; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }
    cout << "Maximum: " << max << endl;
    
    return 0;
}

2. Multidimensional Arrays

2D Arrays

#include <iostream>
using namespace std;

int main() {
    // Declaration and initialization
    int matrix[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    
    // Accessing elements
    cout << matrix[0][0] << endl;  // 1
    cout << matrix[2][2] << endl;  // 9
    
    // Traversing 2D array
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }
    
    return 0;
}

3D Arrays

#include <iostream>
using namespace std;

int main() {
    int arr[2][3][4];  // 2 pages, 3 rows, 4 columns
    
    // Initialization
    int value = 1;
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 3; j++) {
            for (int k = 0; k < 4; k++) {
                arr[i][j][k] = value++;
            }
        }
    }
    
    return 0;
}

3. Arrays and Functions

#include <iostream>
using namespace std;

// Passing array to function
void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}

// Modifying array in function
void doubleArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        arr[i] *= 2;
    }
}

int main() {
    int arr[5] = {1, 2, 3, 4, 5};
    printArray(arr, 5);
    doubleArray(arr, 5);
    printArray(arr, 5);
    return 0;
}

4. C-style Strings

Character arrays terminated by null character ('\\0'):

#include <iostream>
#include <cstring>
using namespace std;

int main() {
    // Declaration
    char str1[20] = "Hello";
    char str2[] = "World";
    char str3[10];
    
    // Input
    cin >> str3;  // Reads until whitespace
    cin.getline(str3, 10);  // Reads entire line
    
    // String functions
    cout << strlen(str1) << endl;  // Length: 5
    strcpy(str3, str1);  // Copy
    strcat(str1, str2);  // Concatenate
    cout << strcmp(str1, str2) << endl;  // Compare
    
    return 0;
}

5. C++ String Class

The string class provides better string handling:

#include <iostream>
#include <string>
using namespace std;

int main() {
    // Declaration and initialization
    string str1 = "Hello";
    string str2("World");
    string str3;
    
    // Input
    cin >> str3;  // Single word
    getline(cin, str3);  // Entire line
    
    // String operations
    cout << str1.length() << endl;  // Length
    cout << str1.size() << endl;    // Same as length()
    
    // Concatenation
    string result = str1 + " " + str2;
    cout << result << endl;
    
    // Comparison
    if (str1 == str2) {
        cout << "Equal" << endl;
    }
    
    // Accessing characters
    cout << str1[0] << endl;  // 'H'
    cout << str1.at(0) << endl;  // 'H'
    
    // Substring
    string sub = str1.substr(0, 3);  // "Hel"
    
    // Find
    int pos = str1.find("ell");  // Returns position or -1
    
    // Replace
    str1.replace(0, 2, "Hi");  // Replace 2 chars from position 0
    
    return 0;
}

6. String Functions

FunctionDescription
length() / size()Returns string length
empty()Checks if string is empty
append()Appends string
insert()Inserts string at position
erase()Removes characters
replace()Replaces substring
find()Finds substring
substr()Extracts substring
compare()Compares strings

7. Array of Strings

#include <iostream>
#include <string>
using namespace std;

int main() {
    // Array of strings
    string names[3] = {"Alice", "Bob", "Charlie"};
    
    for (int i = 0; i < 3; i++) {
        cout << names[i] << endl;
    }
    
    // 2D array of characters (C-style)
    char words[3][20] = {"Hello", "World", "C++"};
    
    return 0;
}

Summary

TopicKey PointsDifficulty
ArraysCollection of same-type elements in contiguous memory, indexed accessBeginner
Multidimensional ArraysArrays of arrays (2D, 3D), useful for matrices and tablesIntermediate
C-style StringsCharacter arrays terminated by null character, use cstring functionsBeginner
C++ String ClassObject-oriented string handling, dynamic sizing, rich member functionsIntermediate
String Functionslength(), substr(), find(), replace(), compare(), etc.Intermediate
Arrays and FunctionsPassing arrays to functions, arrays are passed by referenceIntermediate

Frequently Asked Questions

Q1: What is the difference between C-style strings and C++ string class?

C-style strings are character arrays terminated by null character ('\\0'), requiring manual memory management and functions from cstring header. C++ string class is an object-oriented approach with automatic memory management, dynamic sizing, and rich member functions. String class is safer and easier to use.

Q2: Can I change the size of an array after declaration?

No, static arrays have a fixed size that cannot be changed after declaration. If you need a resizable array, use dynamic arrays with pointers and new/delete, or better yet, use the STL vector class which provides dynamic sizing and automatic memory management.

Q3: What happens if I access an array element beyond its bounds?

Accessing array elements beyond bounds leads to undefined behavior. It may read garbage values, corrupt memory, or cause program crashes. C++ doesn't perform bounds checking for arrays, so you must ensure valid indices. Use the string class's at() method which throws exceptions for invalid indices.

Q4: How do I pass a 2D array to a function?

When passing a 2D array, you must specify at least the column size in the function parameter. For example:void func(int arr[][3], int rows). Alternatively, you can pass it as a pointer to pointer or use STL vector of vectors for more flexibility.

Q5: What is the difference between strlen() and string.length()?

strlen() is a C function that counts characters until null terminator in C-style strings.string.length() is a C++ string class method that returns the number of characters stored. Both return the same value, but length() is type-safe and part of the string object.

Q6: Can I use the + operator to concatenate C-style strings?

No, you cannot use + operator with C-style strings (character arrays). You must use strcat()function from cstring header. The + operator works only with C++ string class objects, which is one reason why string class is preferred in modern C++.

Q7: How are arrays stored in memory?

Arrays are stored in contiguous memory locations. For a 1D array, elements are stored sequentially. For a 2D array, elements are stored row-wise (row-major order). This contiguous storage makes arrays cache-friendly and efficient for iteration, but requires knowing the size in advance.

Q8: When should I use arrays vs vectors?

Use arrays when size is fixed and known at compile time, and you need maximum performance. Use vectors when size may change, you need dynamic allocation, or you want automatic memory management. In modern C++, vectors are generally preferred unless you have specific performance requirements or are working with legacy code.

Conclusion

Arrays and strings are fundamental building blocks in C++ programming that every developer must master. Arrays provide efficient storage and access for collections of data, while strings enable text manipulation and processing. Understanding both C-style strings and the C++ string class gives you flexibility to work with different codebases and choose the right tool for each situation.

The concepts covered in this guide—from basic array operations to advanced string manipulation—form the foundation for more complex data structures and algorithms. Whether you're working with simple lists of numbers or processing complex text data, the skills you've learned here will be invaluable throughout your programming career.

As you continue learning C++, remember that while arrays are powerful, the Standard Template Library (STL) provides containers like vector, list, and string that offer more safety and convenience. However, understanding arrays deeply helps you appreciate these higher-level abstractions and use them more effectively.

Related Links

🔹 Author: Dr. J. Siva Ramakrishna

🔹 Institution: Narayana Engineering College, Gudur

🔹 Last Updated: 9 January 2026