I am a newbie to C++ and I've tried to write a simple string reverse program. When I compile it, everything is OK, but when I run it, I get the following error:
terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_S_construct null not valid Aborted (core dumped) What I am doing wrong? Here is my code.
#include <iostream> using namespace std; string reverse_string(char* argv[], int i); int main(int argc, char* argv[]) { for (int i = 0; i < argc; i++) { cout << reverse_string(argv, i) << endl; } return 0; } string reverse_string(char* argv[], int i) { string arg = argv[i + 1]; string output; int length = arg.length(); for (int index = 1; index <= length; index++) { output += arg[length-index]; } return output; }
argv[i+1]. See it live.std::stringfrom a nullchar*at some point.argv[argc], which happens on your last iteration, is a null pointer.