Sparker0i
Sparker0i

Reputation: 1851

Array not displaying properly when passed to a function as pointer

Given below is my main() function:

int main()
{
    int N = 4;
    int A[N][N] = {
        {1 , 0 , 0 , 0},
        {1 , 1 , 0 , 1},
        {0 , 1 , 0 , 0},
        {1 , 1 , 1 , 1}
    };
    for (int i = 0; i < N; ++i)
    {
        for (int j = 0; j < N; ++j)
            cout << A[i][j] << " ";
        cout << "\n";
    }
    cout << "\n";
    printSolution(N , *A);
    cout << "\n";
    return 0;
}

Here I had declared a 4x4 array with values. Given below is printSolution where I am passing a pointer to the array inside it.

void printSolution(int N , int *sol)
{
    for (int i = 0; i < N; ++i)
    {
        for (int j = 0; j < N; ++j)
            cout << *((sol + i) + j) << " ";
        cout << "\n";
    }
}

Given below is the output:

1 0 0 0
1 1 0 1
0 1 0 0
1 1 1 1

1 0 0 0
0 0 0 1
0 0 1 1
0 1 1 0

As it is visible in the output, the for loop inside the main function printed the array correctly, whereas the printSolution() function could not print it properly. Why is that so?

Upvotes: 0

Views: 76

Answers (1)

bipll
bipll

Reputation: 11940

*((sol + i) + j)

Say, for i = 2 and j = 2 this is merely *(sol + 4), the element in row 1 column 0 (exactly what is printed.)

You probably want *((sol + i * N) + j).

Upvotes: 4

Related Questions