0

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?

5
  • 3
    The question aside, this is C++ -- you should be using <array> or <vector>. Commented Jul 24, 2018 at 10:34
  • I have been told to use pointers, that's why Commented Jul 24, 2018 at 10:35
  • 5
    Ah. Another instructor teaching C first... he shouldn't be doing that... Commented Jul 24, 2018 at 10:36
  • @Ali , operator to '*' must be a pointer Commented Jul 24, 2018 at 10:42
  • 2
    int A[N][N] is not a valid declaration since N is not a constant expression. Many compilers allow it anyway as an unofficial extension called "variable length arrays", but those can bite you in tricky ways. Use constexpr int N = 4; (or const int N = 4;) instead. Commented Jul 24, 2018 at 11:11

1 Answer 1

4
*((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).

Sign up to request clarification or add additional context in comments.

6 Comments

Wouldn't this be an undefined behaviour? sol is a pointer to {1 , 0 , 0 , 0}, accessing other elements beyond this array is UB, no?
@KillzoneKid "A declaration of the form T a[N];, declares a as an array object that consists of N contiguously allocated objects of type T." Op passes *A as function's argument which is the first row of the array, other rows following contiguously.
@bipll the size N of the array sol points to is 4, it is not pointing to 1D array of int the size of N*4
@KillzoneKid: indeed, pedantically sol[4] (A[0][4]) is UB. In practice, we read A[1][0].
@Jarod42 Would this be a better example of this kind of UB? ideone.com/dErrGU
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.