Menu
Coddy logo textTech

C-style Strings Part 2

Part of the Fundamentals section of Coddy's C++ journey — lesson 68 of 74.

It's important to remember that when you declare a C-style string with a specific size, you need to allocate enough space for the characters you want to store, plus one extra space for the null character.

For example:

// Correct: "Hello" needs 6 spaces
// (5 letters + '\0')
char str1[6] = "Hello";
// Wrong: Array too small!
// "Hello" needs 6 spaces, but only 5 given
char str2[5] = "Hello";
// Error: won't compile - only 5 slots for 6 characters ('H','e','l','l','o','\0')
// Correct: Extra space is fine
// More than enough space (10 > 6 needed)
char str3[10] = "Hello";
// Example showing character count:
char name[5] = "John";  // Needs 5 spaces:
// J + o + h + n + '\0' = 5 characters

You can access individual characters in a C-style string using array notation:

char str[] = "Hello";
char first = str[0]; // 'H'
char third = str[2]; // 'l'

You can also modify characters in a C-style string, as long as you don't exceed the bounds of the array:

char str[] = "Hello";
str[0] = 'J';
std::cout << str; // Outputs "Jello"

However, you cannot directly assign a new string to a C-style string after it's declared. You'll need to use functions like strcpy to copy strings, which we'll cover in later lessons.

Try it yourself

This lesson doesn't include a code challenge.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals