Home > Enterprise >  What's being compared to the last element of the array?
What's being compared to the last element of the array?

Time:09-21

There's a behavior that I don't understand, the c variable is supposed to increase by one every time an element of the array isn't equal to the one next to it, but there's one increment that's done automatically which increases c by one. I think this is because the last element of the array is compared to something which isn't equal to it. Why is this happening? Or if I'm right what's the thing that the last element is compared to?

#include <iostream>

int main() {
    int n, c = 0;
    std::cin >> n;
    std::string s[n];
    for (int i = 0; i < n; i  ) {
        std::cin >> s[i];
    }
    for (int i = 0; i < n; i  ) {
        if (s[i] != s[i 1]) {
            c  ;
        }
    }
    std::cout << c;
}

CodePudding user response:

std::string s[n]; is creating what is known as a "Variable-Length Array", which is NOT part of standard C , but is supported as an extension by some compilers. Don't rely on this. Use std::vector instead for a dynamic-length array whose length is not known until runtime.

But, more importantly, your 2nd loop has undefined behavior. The valid indexes for the s[] array's elements are 0..n-1, so on that loop's last iteration, s[i] accesses the last string in the array, and s[i 1] accesses out of bounds, so the value that s[i] is compared to is indeterminate (if the code doesn't just crash outright from accessing invalid memory).

CodePudding user response:

s[s.length()] == ‘\0

From here: https://www.cplusplus.com/reference/string/string/operator[]/

“If pos is equal to the string length, the function returns a reference to the null character that follows the last character in the string (which should not be modified).”

  • Related