Search code examples
c++for-loopg++nested-loopsstdvector

When I change array to vector, the program is abnormal


When I use an array, the following code works well. I tried to replace array with std::vector, but found that procedures often appear abnormalities, need to run more times. Anything I missed? I am using g++ 10.3.

#include <iostream>
#include <vector>

int main() {
    int n = 3;
    for (int k = 1; k <= 4; ++k) {
//        int *A = new int[k]();
        std::vector<int> A(k, 0);
        int i = 0;
        for (; i >= 0; A[i]++) {
            for (int j = 0; j < k; ++j) {
                std::cout << A[j] << " ";
            }
            std::cout << "\n";
            for (i = k - 1; i >= 0 && A[i] == n - 1; i--)
                A[i] = 0;
        }
    }
    return 0;
}

Solution

  • In this for loop in its third part

    for (; i >= 0; A[i]++) {
                   ^^^^^^
    

    the variable i can be equal to -1 after the inner loop

    for (i = k - 1; i >= 0 && A[i] == n - 1; i--)
    

    where the same variable i is used (for example when k is equal to 1).

    So it is unimportant whether you are using a vector or an array. The program has undefined behavior.