samedi 28 mars 2020

Is pointer addition with an int variable different from addition with an int literal?

Consider this snippet of code, trying to check if two arrays are equal:

int arr1[5] = {1,2,3,4,5};
int arr2[5] = {1,2,3,4,5};

int *p1 = arr1;
int *p2 = arr2;

if (end(arr1) - p1 == end(arr2) - p2) // Check if sizes are equal
{
    for (size_t i = 0;
         p1 != end(arr1);
         ++i){
             if (*(p1 + i) != *(p2 + i)){ // Check if each ith element is equal
                 cout << "Arrays not equal!" << endl;
                 return 0;
             }
         }
    cout << "Arrays equal!" << endl;
    return 0;
}
else // Not equal if sizes don't match
{
    cout << "Arrays not equal!" << endl;
    return 0;
}

When I run this code, I end up getting "Arrays not equal!". So, I was looking into the if condition, when I noticed that *(p1 + i) for the first i, i.e., i = 0, seems to give a value of 32766, whereas if I write *(p1 + 0), I'm getting the first element of arr1 as expected. Why does this happen?

Aucun commentaire:

Enregistrer un commentaire