Gaurav Arora
Gaurav Arora

Reputation: 183

Bug in C++ Code: setting one variable to zero causes unrelated variable to become zero

Why does the value of variable n2 get changed to 0 in the below code after the execution of the statement arr[26]={0}; ,(I realised this while debugging) while memset(arr,0,sizeof(arr)); works perfectly.

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

int main()
{
    long int n1,n2;
    int count=0,flag;
    int arr[26] = {0};
    cin>>n1>>n2;
    string box1[n1];
    string box2[n2];

    for(int j=0;j<n1;j++)
    cin>>box1[j];

    for(int j=0;j<n2;j++)
    cin>>box2[j];

    count=0;

    for(int i=0;i<n1;i++)
    {   

        for(int j=0;j<n2;j++)
        {
            arr[26]={0}; // after the execution of this statement, n2 changes to 0.. WHY???
            //memset(arr,0,sizeof(arr)); // If i use memset , things work correctly
            cout<<n2<<endl; //n2 becomes zero
            for(int k=0;k<box1[i].length();k++)
                arr[box1[i][k]-'A']++;

            for(int k=0;k<box2[j].length();k++)
                arr[box2[j][k]-'A']++;

            for(int k=0;k<26;k++)
            {
                if(arr[k]>=1)
                    continue;
                else
                {
                    flag=1;
                    break;
                }

            }

        }

    }
    printf("%d",count);
   return 0;
}

Can anyone explain what's wrong with :

arr[26] = {0};

Upvotes: 0

Views: 207

Answers (1)

jaropelk
jaropelk

Reputation: 46

You declare arr as:

int arr[26] = {0};

Which means valid indexes for it are 0-25, making 26 spots total. Then when you write to arr[26], you are actually writing outside of the array, and overwriting memory that your compiler assigned to n2.

If you want to be able to index to 26, you need to declare space for 27 ints:

int arr[27] = {0};

Also the code:

arr[26]={0}; // after the execution of this statement, n2 changes to 0.. WHY???

Only assigns to element 26 in the array. It does not zero out the entire array or anything like that. The way to zero the entire array at runtime is with arr = {0} or using the memset code you already have.

Upvotes: 3

Related Questions