C++ C-Style Strings (Character Arrays)

C-style strings in C++ are arrays of characters terminated by a null character ('\0'). They are inherited from the C programming language and are stored in contiguous memory.

1. Declaration of C-Style Strings

A C-style string is declared as a character array.

C++
Syntax and example of declaration
char str[10];

// With initialization
char name[6] = "Hello";

2. Null Terminator

Every C-style string ends with a null character '\0'. It marks the end of the string. Without it, the string functions may produce undefined behavior.

C++
Example showing null terminator
char word[] = {'H', 'i', '\0'};

3. Input and Output

C-style strings can be displayed using cout and taken as input using cin or gets (deprecated).

C++
Example: Input and Output of C-style string
#include <iostream>
using namespace std;

int main() {
    char name[50];
    cout << "Enter your name: ";
    cin >> name;
    cout << "Hello, " << name;
    return 0;
}

4. Common String Functions

The library provides built-in functions to work with C-style strings.

C++
Example: Using string functions
#include <iostream>
#include <cstring>
using namespace std;

int main() {
    char str1[20] = "Hello";
    char str2[20] = "World";

    strcat(str1, str2);
    cout << "Concatenated string: " << str1 << endl;
    cout << "Length: " << strlen(str1) << endl;

    return 0;
}

5. Common Mistakes

1. Forgetting to allocate space for the null terminator. 2. Using gets() which is unsafe and deprecated. 3. Buffer overflow due to insufficient array size. 4. Not including when using string functions.

Conclusion

C-style strings use character arrays and a null terminator to store text. While powerful, they require careful memory handling. Modern C++ prefers std::string for safer string manipulation.