c++ - Function will return a string which holds the section between the two indexes -


i have problem how can return string between ranges(given user) of char array. example:

  entered string “my name john". 

start index: 3 stop index: 6 function return “name”

my code here address output

#include <iostream> #include <conio.h> #include <string> #include <cstring> using namespace std;  string *section(char*ary, int index_1, int index_2) {     string sec=ary;     string *str;     str = &sec;     *str = sec.substr(index_1, index_2);     return str; }   int main() {     int starting_index = 0;     int ending_index = 0;      char *ptr;     ptr = new char[200];     int = 0;     char ch = _getche();     while (ch != 13)     {          ptr[i] = ch;         i++;         ch = _getche();     }     (int j = 0; j < i; j++)     {         cout << ptr[j];     }     cout << endl;      cout << "enter start index: " << endl;     cin >> starting_index;     cout << "enter end index: " << endl;     cin >> ending_index;     cout<<section(ptr, starting_index, ending_index);     delete[] ptr;   system("pause"); } 

your main problem return pointer. in other words, return address of string object. has 2 effects. firstly, pass returned address cout, instead of pointed string. if intention print string, should have dereferenced pointer. there's problem. returned pointer invalid, because pointed local object destroyed when function ended. may not dereference pointer. it's useless.

both issues can solved returning string value section, rather address.

please explain difference between these 2 prototype. string section( paramerters ) , string *section( paramerters )

the part on left side of function name (which section) type of object function returns. difference between string , string* types latter pointer type. value of pointer memory address pointed object located. so, former function prototype declares function returns string, while latter declares function returns pointer string.

few other tips besides bug: function fiddles pointlessly pointers. str variable unnecessary. never use index arguments. in main unnecessary dynamic allocation.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -