CharacterPointer in C++ -


i have piece of code follows:

char* foo(char* str1) {       str1 = "some other text";     cout << "string inside function::" << str1 << endl;      return str1; }  int main() {       char* str = "this string";      cout << "string before function call::" << str << endl;     foo(str);     cout<<"string after function call::"<<str<<endl;      return exit_success; } 

but cout after function call gives me "this string" though have changed in foo function. i'm confused here although know has got me not passing correct address.

// adding & (aka pass reference) after char* can modify pointer passed foo function // must understand place in memory!!! void foo(char*& str1) {       // string saved in global section , here     // changed not text in str1 pointer     str1 = "some other text";      cout << "string inside function::" << str1 << endl; }  // way change pointer pass pointer pointer void foo_v2(char** str1) {     // should dereference pointer pointer (* before str1)     *str1 = "some other text"; }  // in case change content @ pointer str1 // dangerous, can replace content not memory under str1 // return address if string placed in stack memory. // such terrible things occurred if string copied str1  // occupied more bytes can contained in str1 // more safe way using example std::string void foo2(char* str1) {          char *s = "some other text";      strcpy(str1, s, strlen(s)); }  int main() {       char* str = "this string";      cout << "string before function call::" << str << endl;     foo(str);     cout<<"string after function call::"<<str<<endl;      return exit_success; } 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -