StrForeachPtrIdx

Table of Contents

StrForeachPtrIdx

Description

Iterate over each character pointer chrptr of the given Str str at each index idx. This macro is a direct alias for VecForeachPtrIdx specialized for Str. The variables chrptr and idx are declared and defined by the underlying macro.

Parameters

NameDirectionDescription
strin,outStr to iterate over.
chrptrinName of the pointer variable to be used which will point to the character at the iterated index idx. The type of chrptr will likely be a pointer to the character type used by the Str implementation (e.g., char*).
idxinName of the variable to be used for iterating over indices (i64).

Usage example (Cross-references)

    // Deadend test: Make idx go out of bounds in StrForeachPtrIdx by modifying string during iteration
    bool test_str_foreach_ptr_idx_out_of_bounds_access(void) {
    printf("Testing StrForeachPtrIdx where idx goes out of bounds (should crash)\n");
    
    Str s = StrInitFromZstr("Programming Test"); // 16 characters
    
    // StrForeachPtrIdx (VecForeachPtrIdx) has explicit bounds checking: if ((idx) >= (v)->length) LOG_FATAL(...)
    StrForeachPtrIdx(&s, chr_ptr, idx, {
    printf("Accessing idx %zu (s.length=%zu): '%c'\n", idx, s.length, *chr_ptr);
    // Test StrForeachPtrIdx macro
    bool test_str_foreach_ptr_idx(void) {
    printf("Testing StrForeachPtrIdx\n");
    
    Str s = StrInitFromZstr("Hello");
    // Build a new string by iterating through each character pointer with its index
    Str result = StrInit();
    StrForeachPtrIdx(&s, chrptr, idx, {
    // Append the character (via pointer) and its index to the result string
    StrWriteFmt(&result, "{c}{}", *chrptr, idx);

Share :