Weird logic error?

Now consider these 2 codes:


for the input:
7
1 3 1 3 2 1 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int a[4];
int n;
int main()
{
    cin >> n;
    for(int i = 1; i <= n; i++)
    {
        int num;
        cin >> num;
        a[num]++;
    }

    cout << min(a[1], min(a[2], a[3]));

    return 0;
}


outputs: 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int main()
{
    int a[4];
    int n;
    cin >> n;
    for(int i = 1; i <= n; i++)
    {
        int num;
        cin >> num;
        a[num]++;
    }

    cout << min(a[1], min(a[2], a[3]));

    return 0;
}


outputs undefined garbage


Now what I don't get is these 3 things:

1.
1
2
    int a[4];
    int n;

Either being outside the main function or inside. why does that make such a BIG difference


2.
a[num]++;

This syntax is not something I ever used or saw before o.o how does this one work?

3.
the reason it ouputs 2?
Last edited on
Your array is not big enough to hold 7 elements.

a[num]++; is the same as a[num] += 1; or a[num] = a[num] + 1;. It increases the value of a[num] by 1.
Last edited on
0. index array goes from 0 to size-1. you start from 1 and write over bounds.
both codes have undefined behaviour.

1. don't see the point in analysing undefined code.
perhaps a compiler writer may help you.

2. surely you have worked with arrays before and knows that `a[num]' means to access, and surely you have seem post-increment (it's on your loop) so you should be able to figure out.
perhaps this will help you http://en.cppreference.com/w/cpp/language/operator_precedence
(a[num]) ++

3. as I said, both have undefined behaviour.
once you fix the out-of-bounds access you may have issues with non-initialized variables (globals are initialized to 0).
then you may do a desk test.
[Program 2] outputs undefined garbage.

So does program 1. It just happens to output garbage that matches what you expect.

The thing to drill into your head repeatedly is that you can't access an array out of bounds. The results are undefined. Maybe it will work. Maybe it won't. Maybe it works 99 times out of 100. Maybe it works fine until you recompile program or run it on a different computer.

In the first program, the array a is zero-initialized because it's a global. In the second program array a is a local variable. That means it's allocated on the stack, in space that was used by other local variables involved in the startup code. So the array is allocated in memory that already contains something.
Topic archived. No new replies allowed.