-1

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;
}
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • Do note that `std::string s[n];` is not valid C++. Variable length arrays are only possible with compiler extensions. See [Why aren't variable-length arrays part of the C++ standard?](https://stackoverflow.com/q/1887097/11082165) – Brian61354270 Sep 20 '21 at 22:13
  • 2
    1) `s[n]` is a variable-length array, which is non-standard 2) Your second `for` loop will access out of bounds memory, which is undefined behavior; at that point, all bets are off – Stephen Newell Sep 20 '21 at 22:13

2 Answers2

1

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).

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
-1
s[s.length()] == ‘\0’

From here: https://www.cplusplus.com/reference/string/string/operator%5B%5D/

“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).”

bad_coder
  • 11,289
  • 20
  • 44
  • 72
iverson
  • 1
  • 1