#include <cstdlib>
#include <iostream>

static void fillArray(int **array);

int main() {
    //allocating a 2D array
    int **array;
    array=new int*[10];
    for(int i=0;i<10;i++)
        *(array+i)=new int[5];
    //sending this array to a function
    fillArray(array);
    for(int i=0;i<10;i++)
        for(int j=0;j++;j<5)
            std::cout<<array[i][j];
    for(int x=0;x<10;x++)
        delete[] array[x];
    delete[] array;
    return 0;
}

static void fillArray(int **array) {
    int x=0;
    for(int i=0;i<10;i++)
        for(int j=0;j<5;j++) {
            array[i][j]=x;
            x++;
        }
}

compiles, but does nothing.

Dani AI

Generated

The program compiles but never prints because the inner print loop's control expressions are in the wrong places. As observed, the middle expression of a for is the condition and it is evaluated before the loop body runs. Putting a post‑increment there makes the test return the old value; since it starts at zero the condition is false immediately and the loop body is skipped. That is the single logical fault causing "does nothing."

The advice from to use unsigned int does not fix this logic error and can introduce other traps (wraparound, confusing signed/unsigned comparisons). Enabling compiler warnings (for example -Wall -Wextra -pedantic) catches many suspicious constructs. When an index type is needed, std::size_t is the conventional choice for container indices, but the core issue here is loop control, not the signedness of the index.

A safer, clearer approach uses RAII and standard containers. Example using a single contiguous buffer (better cache behavior and simpler ownership):

#include <vector>
#include <iostream>

const std::size_t rows = 10, cols = 5;
std::vector<int> data(rows * cols);

for (std::size_t i = 0; i < rows; ++i)
    for (std::size_t j = 0; j < cols; ++j)
        data[i * cols + j] = static_cast<int>(i * cols + j);

for (std::size_t i = 0; i < rows; ++i) {
    for (std::size_t j = 0; j < cols; ++j)
        std::cout << data[i * cols + j] << ' ';
    std::cout << '\n';
}

Additional checks: run with sanitizers (-fsanitize=address,undefined) or valgrind, step through with a debugger, and prefer std::vector/std::array over raw new[]/delete[] to avoid lifecycle mistakes. For the immediate fix is to swap the loop components so the condition is the relational test and the increment is the ++ expression.

Recommended Answers

All 2 Replies

line 16 is for(int j=0;j++;j<5) , it should be for(int j=0;j<5;j++) (the j++ and the j < 5 are swapped around).

Use unsigned int instead of int.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.