-1

I have written a small program which compares two arrays with custom array size. Whenever I set the array size to 4, the program does not work correctly on comparing the fourth member of each array. (when I set x to 4, the fourth array members does not get compared correctly)

This is the code:

#include <iostream>
using namespace std;

int main()
{
    int x;
    std::cin >> x;
    int i =1;
    int arr[x];
    int arr2[x];
    while(i <= x)
    {
        std::cout << "Enter row " << i << " of arr\n";
        std::cin >> arr[i];
        i++;
    }
    i = 1;
    while(i <= x)
    {
        std::cout << "Enter row " << i << " of arr2\n";
        std::cin >> arr2[i];
        i++;
    }
    for(int a = 0;a <= x;a++)
    {
        if(arr[a] == arr2[a])
            std::cout << "row " << a << " is true\n";
    }
}

2 Answers2

1

You have an out of bound access, which yields undefined behavior. Recall that indices into raw arrays start with zero, not with one. Hence,

int i = 0;

is the correct initialization of the index, while the first loop must be changed to

while (i < x) { /* ... */ }

Then, the assignment of i needs again to be adjusted to

i = 0;

and the two remaining loops to

while (i < x) { /* ... */ }

for (int a = 0; a < x; a++) { /* ... */ }

As a side note, you are using variable length arrays (arr and arr2), which is non-standard C++ (see this thread for more info). Prefer std::vector for a simple container with runtime-dependant size.

lubgr
  • 37,368
  • 3
  • 66
  • 117
0
i = 1;
while(i <= x)
{
    std::cout << "Enter row " << i << " of arr2\n";
    std::cin >> arr2[i];
    i++;
}

you are storing element in array starts with 1 index

for(int a = 0;a <= x;a++)
{
    if(arr[a] == arr2[a])
        std::cout << "row " << a << " is true\n";
}

But comparing by starting from 0 index. keep consistency either start from 0 or 1

for(int a = 1;a <= x;a++)
{
    if(arr[a] == arr2[a])
        std::cout << "row " << a << " is true\n";
}

it will work..