Search code examples
c++pointersstdarray

Correct way to loop through std::array<char*, N>


Consider the following std::array of pointers to char:

std::array<char*, 10> m_arr;

I know I can loop through the array using the following code

for(size_t i {0}; i < m_arr.size(); i++) {
            std::cout << m_arr.at(i) << std::endl;
    }

But this approach throws "Access violation reading location" exception, when the i-th element is not assigned correctly. For example the following code assigns the first two elements but the third element, m_arr.at(3), raises the aforementioned error:

    // test variables
    int x {100};
    double y {3.14};
    int* x_ptr {&x};
    double* y_ptr {&y};

    // std::array of pointer to char
    std::array<char*, 10> m_arr;

    // set the first two elements of m_arr
    char buf1[16];
    sprintf_s(buf1, "%p", x_ptr);
    m_arr.at(0) = buf1;
    char buf2[16];
    sprintf_s(buf2, "%p", y_ptr);
    m_arr.at(1) = buf2;

    for(size_t i {0}; i < m_arr.size(); i++) {
            std::cout << m_arr.at(i) << std::endl;
    }

I found out a quick fix around this by checking the i-th element with the last element of the array to skip unassigned elements but obviously that's not a clean answer

for(size_t i {0}; i < m_arr.size(); i++) {
        if(m_arr.at(i) != m_arr.back()) {
            std::cout << m_arr.at(i) << std::endl;
        }
    }

I believe there is a better way to loop through this array and avoid the error. Thank you in advance for your help.


Solution

  • Initialize your array:

    std::array<char*, 10> m_arr{}; // nullptr initialized
    

    then you might check safety for non-nullptr value:

    for (auto ptr : m_arr) {
        if (ptr) std::cout << ptr << std::endl;
    }