0

I am trying to write a program to find prefix sum. It is showing error: invalid types 'int[int] for array subscript for single dimensional array code1

#include <bits/stdc++.h>
using namespace std;

long long a[(int)1e5 + 50];
int n;

void buildPrefixSum() { // O(n)
   for(int i = 1; i < n; i++) {
       a[i] += a[i - 1];
   }

}

int getSum(int i, int j) { // O(1)
   int sum = a[j];
   if(i > 0) sum -= a[i - 1];
   return sum;
}

int main()
{
    ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    int t,a,b;
    cin >> n;
    for(int i = 0; i < n; i++)
    {
        cin >> a[i];
    }
    buildPrefixSum();
    cin >> t;
    while(t--)
    {
        cin >> a >> b;
        cout << getSum(a,b) << "\n";
    }
}

But when I change the main function to this, the code runs properly.code2

int main() {
    cin >> n;
    for(int i = 0; i < n; i++) {
        cin >> a[i];
    }
    buildPrefixSum();
    int q;
    cin >> q;
    while(q-- > 0) {
        int a, b;
        cin >> a >> b;
        cout << getSum(a, b) << endl;
    }
    return 0;
}

I don't understand the difference between the two codes. Can anyone please clarify the mistake I made in the main function of the first code?

3
  • 1
    Look at where you're declaring a and what types you're declaring. Commented Jul 20, 2020 at 6:20
  • 1
    In the first snippet, in main(): int t,a,b; The local variable a eclipses the global variable with same name. (The global is still there but you cannot access it in the local scope.) Commented Jul 20, 2020 at 6:25
  • 2
    stackoverflow.com/a/31816096/1387438 Commented Jul 20, 2020 at 6:37

1 Answer 1

1

In you first code block, your long long array a is being "shadowed" (hidden) by the a in the line:

int t,a,b;

You'll find the problem boils down to this:

int main() {
    int a;
    a[0] = 7; // error: invalid types 'int[int]' for array subscript
}

In your second code block, the declaration of the non-array a doesn't happen until after you've populated the array a - the shadowing only exists within the while loop and therefore does not raise an error.

I suspect this problem may not have occurred had you just used decent variable names :-)

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

Comments

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.