Arrays and Strings
C strings are null-terminated character arrays; C++ std::string owns its storage and tracks its length.
What is Arrays and Strings?
C strings are null-terminated character arrays; C++ std::string owns its storage and tracks its length.
Traverse fixed arrays and safely measure text.
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.
C and C++ code examples
main.c
#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
C++
main.cpp
#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
C exposes small procedural APIs and makes representation details explicit.
C++
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.