Learning Hub Search Ctrl K

Legacy C++ › 2. Pointers, References and Memory

Arrays and C Strings

Built-in arrays, pointer arithmetic, char arrays and <cstring>.

beginner #arrays#pointer-arithmetic#c-strings#cstring

Explanation

A built-in array is a fixed-size, contiguous block: int a[5];. It does not know its own size and decays to a pointer to its first element when passed to a function. Indexing a[i] is defined as *(a + i), and pointer arithmetic moves in units of the element type.

A C string is a char array ending with a null terminator '\0'. A string literal such as "hi" is a const char[3] ('h', 'i', '\0'). The <cstring> functions (strlen, strcpy, strcmp, strcat) assume the terminator exists.

Example

#include <cstring>
#include <iostream>

int sum(const int* a, std::size_t n) {         // array arrives as a pointer
    int s = 0;
    for (std::size_t i = 0; i < n; ++i) s += a[i];
    return s;
}

int main() {
    int nums[5] = {1, 2, 3, 4, 5};
    std::size_t count = sizeof(nums) / sizeof(nums[0]);   // 5, only works on a real array
    std::cout << sum(nums, count) << "\n";

    const int* p = nums;
    std::cout << *(p + 2) << " " << p[2] << "\n";         // both 3

    char name[16];
    std::strncpy(name, "Ada", sizeof(name) - 1);
    name[sizeof(name) - 1] = '\0';                         // guarantee termination
    std::cout << name << " (" << std::strlen(name) << ")\n";

    if (std::strcmp(name, "Ada") == 0) std::cout << "equal\n";   // == would compare addresses
    return 0;
}

Common pitfalls

  • Buffer overflow: strcpy / strcat / gets do not check sizes. Prefer strncpy with manual termination, or better std::string.
  • sizeof(arr) inside a function gets the size of a pointer, not the array.
  • a == b on two C strings compares addresses; use strcmp.
  • Out-of-bounds access is undefined behavior; there is no checking.
  • Modifying a string literal (char* s = "x"; s[0] = 'y';) is undefined. Declare const char*.

Legacy vs modern

Prefer std::string and std::vector. C++11 adds std::array<T,N> (fixed size, knows its size) and range-based for over arrays; C++20 adds std::span for passing array views.

Exercises

1. How many bytes does char s[] = "hello"; occupy?

6: five letters plus the terminating '\0'.

2. Write your own strlen.
std::size_t mylen(const char* s) { const char* p = s; while (*p) ++p; return p - s; }