-8

If I run this code:

#include<bits/stdc++.h>

using namespace std;

int hourGlass(int x, int y) {
    int sum;
    for (int a=y; a<=y+2; a++) {
        sum += arr[x][a];
        sum += arr[x+2][a];
    }
    return sum;
}

int main(){
    
    int arr[7][7];
    
    for (int i=0; i<=5; i++) {
        for (int j=0; j<=5; j++) {
            cin >> arr[i][j];
        }
    }
    
    for (int i=0; i<=3; i++) {
        for (int j=0; j<=3; j++) {
            cout << hourGlass(i,j);
        }
    }
    
}

It gives the error 'arr' was not declare on this scope. How do I fix this?

cigien
  • 50,328
  • 7
  • 37
  • 78
  • 2
    Use `std::array` instead of a raw array, and add it as a parameter to `hourGlass`. – Dai Aug 25 '20 at 11:20
  • 6
    Unrelated to your problem, but please read [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) as well as [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Some programmer dude Aug 25 '20 at 11:21
  • 3
    Also please invest in [some good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282), or take a few classes. – Some programmer dude Aug 25 '20 at 11:22
  • Named variables, including arrays, only exist in the context where they are declared. A declaration in one function is not magically visible in another. You are expecting `arr`, an array defined in `main()` to be visible in the function `hourGlass()`. It isn't. Try reading any introductory text on C++ if you want to understand this. – Peter Aug 25 '20 at 11:26
  • `sum` is used uninitialized so you will have undefined behavior when you get the code to compile. – Ted Lyngmo Aug 25 '20 at 12:39

2 Answers2

2

Your hourGlass function does not have access to arr which is in the scope of the main function. You can pass arr as a parameter to the function like this:

int hourGlass(int x, int y, int const (&arr)[7][7]) {
  // ...
}

and call the function like this:

hourGlass(i, j, arr)

Also, note that sum is uninitialized in your function, so reading from it invokes undefined behavior.

cigien
  • 50,328
  • 7
  • 37
  • 78
-4

Simply move int arr[7][7] outside of the main() function and put it before int hourGlass(int x, int y). This will make it global, that is, visible to all functions declared after it (not just a single function).

Or, perhaps a better solution (but limited to C++), use some STL container, such as std::vector or std::array, and pass it as a function argument.

FlatAssembler
  • 563
  • 4
  • 20