Arrays and Strings
Traverse fixed arrays and safely measure text.
What is Arrays and Strings?
C strings are null-terminated character arrays; C++ std::string owns its storage and tracks its length.
Important points
- Compile with warnings enabled and fix every warning.
- Know the lifetime and type of every value.
- Validate input and keep array bounds explicit.
See how it works
A C string is an array of characters that ends with '\0'. Click a character to see its index and memory address.
C and C++ code examples
#include <stdio.h>
#include <string.h>
int main(void) {
int values[] = {3, 5, 8, 13};
char name[] = "Ada";
size_t count = sizeof values / sizeof values[0];
printf("%s: %zu values, %zu letters\n", name, count, strlen(name));
return 0;
}
Ada: 4 values, 3 letters
#include <array>
#include <iostream>
#include <string>
int main() {
std::array values{3, 5, 8, 13};
std::string name = "Ada";
std::cout << name << ": " << values.size()
<< " values, " << name.size() << " letters\n";
}
Ada: 4 values, 3 letters
C and C++ comparison
sizeof can determine a local array's element count but not an array received as a pointer parameter. strlen scans for the null terminator; std::string::size is constant time.
C exposes small procedural APIs and makes representation details explicit.
C++ retains the low-level model while adding safer library types and abstractions.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Add invalid and boundary-value inputs.
- Compile with -Wall -Wextra -Wpedantic.
- Move reusable declarations into a header and implementation file.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Sum an Array Add up all values in a list. Easy
- Reverse a String Return the characters of a string in reverse order. Easy