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";
// This might cause problems// 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 charactersYou 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.
Cheat sheet
When declaring C-style strings, allocate space for all characters plus one for the null terminator '\0':
// Correct: "Hello" needs 6 spaces (5 letters + '\0')
char str1[6] = "Hello";
// Wrong: Array too small!
char str2[5] = "Hello"; // This might cause problems
// Correct: Extra space is fine
char str3[10] = "Hello";Access individual characters using array notation:
char str[] = "Hello";
char first = str[0]; // 'H'
char third = str[2]; // 'l'Modify characters within array bounds:
char str[] = "Hello";
str[0] = 'J';
std::cout << str; // Outputs "Jello"Note: You cannot directly assign a new string to a C-style string after declaration. Use functions like strcpy for string copying.
Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison3Variables Part 2
Type DeclarationNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementConditional OperatorRecap - If ElseNested If - Else9Loops
For Loop Part 1While LoopDo While LoopBreakContinueFor Loop Part 2Nested LoopsInfinite LoopsRecap - Dynamic Input12Strings
C-style Strings Part 1C-style Strings Part 2String OperationsString Functions Part 1String Functions Part 2