User6715985 User6715985 - 3 months ago 7
C++ Question

Reverse String (Leetcode) Using C++, Why I cannot return the new string as method

Question: Write a function that takes a string as input and returns the string reversed.

Example: Given s = "hello", return "olleh".

What's wrong with this code?

class Solution {
public:
string reverseString(string s) {

string s2;

for(int i=0; i<s.length(); i++)
s2[i] = s[s.length()-1-i];

return s2;
}
};

Answer

Because the very first iteration of the loop attempts to set s2[0] to the last character of the original string.

The problem is that there is no s2[0]. The s2 string is completely empty. The s2 string is, essentially, an empty array.

Attempting to access the contents of the string using the [] operator accesses the existing character of that string. It doesn't create one, if it doesn't exist.

Even if code execution survives this undefined behavior, on the next iteration of the loop an attempt gets made to set s2[1] to some character. s2[1] does not exist, any more than s2[0] did. And so on. Undefined behavior. Crash.

Instead of setting non-existent values of an empty string, just use push_back() to add each character to s2.

This isn't really a particuarly efficient approach to reversing the contents of the string, of course. But it's a fine first attempt at tackling this introductory task.

Comments