Thread: modifiing pointer in other function

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    C++ has references for such problems
    Code:
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    void create(string *& x)
    {
    	cout << "adr x before: " << x << endl; // not initialized
    	x= new string("aaa"); 
    	cout << "adr x after: " <<  x << endl; 
    }
    
    int main()
    {
    	string *s = 0;          // a pointer to a string ( as in your description )
    	cout << "adr s bevore: " << s << endl; // was initialized to 0
    	create(s);
    	cout << "adr s after: " << s << " = " << *s << endl;
        delete s;   // dont forget about this
    	return 0;
    }
    Kurt
    EDIT: too late, but look at it as a variation of vart's solution
    Last edited by ZuK; 11-26-2006 at 07:34 AM.

  2. #2
    Registered User
    Join Date
    Nov 2006
    Posts
    519
    Quote Originally Posted by ZuK
    Code:
        delete s;   // dont forget about this
    }
    Thank you both! Isn't the destructor called automaticly while the variable *s is going out of scope with the "}" of the main function?

  3. #3
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    No. You have to delete anything that was allocated with new.
    Kurt
    EDIT: The pointer to the string will be destructed ( that's a nop ) but not the object it points to ( the string ).
    Last edited by ZuK; 11-26-2006 at 08:43 AM.

  4. #4
    Registered User
    Join Date
    Nov 2006
    Posts
    519
    so for
    Code:
    {
      ...
      string s;
      ...
    } //*
    the destructor is called at //*

    and for

    Code:
    {
      ...
      string* s = new string();
      ...
    }
    it is not and delete is required.

  5. #5
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    right.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 07-04-2007, 12:46 PM
  2. <Gulp>
    By kryptkat in forum Windows Programming
    Replies: 7
    Last Post: 01-14-2006, 01:03 PM
  3. Function Pointer help
    By Skydt in forum C Programming
    Replies: 5
    Last Post: 12-02-2005, 09:13 AM
  4. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM
  5. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM