0

I tried making a function that would take a string and split the characters up into an array. But I kept getting these "Exception Thrown" and "Exception Unhandled" errors that I don't even understand (I am very new to C++).

string Decrypt(string symbols) {
    int length = symbols.length();
    string symbolsArray[]{""};
    for (int i = 0; i < length; i++)
    {
        symbolsArray[i] = symbols[i];
    }
    cout << symbolsArray;
    return "";
}

exception unhandled

I tried changing the symbolsArray[i] to just a normal integer like symbolsArray[0] and that worked just fine but obviously I don't want to be changing the first element each time.

  • 8
    Arrays in C++ have fixed length. Yours has only one element and can never get any more. Accessing elements that are out of bounds results in undefined behaviour (i.e. possibly a crash as you're seeing). Use `std::vector` if you want something that can grow. – Thomas Apr 27 '23 at 15:29
  • In `symbolsArray[i] = symbols[i];` `symbolsArray[i]` is a `string` and `symbols[i]` is a `char`. Be sure that this is what you want. – user4581301 Apr 27 '23 at 15:30
  • 1
    Stackoverflow usage note: Where possible, and it pretty much always is, reproduce the error message exactly. This problem was cut-n-dried, but when there's ambiguity, the precise wording of the error can often clear that up. – user4581301 Apr 27 '23 at 15:33

1 Answers1

1

symbolsArray is a string array containing just one empty string. You are accessing it out of bounds when you do symbolsArray[i] = symbols[i];. The string array doesn't magically grow when you access an index outside it's current size - rather you invoke undefined behaviour.

See also Undefined, unspecified and implementation-defined behavior.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70