RSS Forums RSS
Please support our C++ advertiser: Programming Forums
Views: 1570 | Replies: 2 | Thread Tools  Display Modes
Reply
Join Date: Aug 2005
Posts: 596
Reputation: SpS is on a distinguished road 
Rep Power: 5
Solved Threads: 31
SpS's Avatar
SpS SpS is offline Offline
Posting Pro

Help C++ Object Pointers Problem

  #1  
Sep 7th, 2005
Hi,

Please see the code below.

void Allocate( char* s )
{
s = (char*)malloc( 100 );
}

int main( )
{
char* s = NULL;
Allocate( s );
strcpy( s,"Test");/*I know that this will fail. b'coz I still have a NULL pointer in s. Initially s was pointing to NULL, and from the function Allocate 100 bytes of memory was allocated in some memory location, and address of s was made to point to that location. But inside the main, s is still pointing to NULL. Pl. correct me if I am wrong.*/

}

Now my question is

void Allocate( Base* s )
{
s = new Base;
}

int main( )
{
Base* obj = NULL;
Allocate( obj );
obj->some_member = 20; // this works...

}
<< moderator edit: added [code][/code] tags >>

So I assume, object pointers are passed to functions in a different way compared to primitive type pointers. Can anyone pl. comment on this.
AddThis Social Bookmark Button
Reply With Quote  
Join Date: Jul 2005
Location: London
Posts: 164
Reputation: Stoned_coder is an unknown quantity at this point 
Rep Power: 4
Solved Threads: 5
Stoned_coder Stoned_coder is offline Offline
Junior Poster

Re: C++ Object Pointers Problem

  #2  
Sep 7th, 2005
All passing is by value unless otherwise specified. As you want the changes reflected back to the calling function you will need to pass either a reference to a pointer a char*& or a pointer to a pointer a char** or alternatively return a pointer by value rather than void.
object pointers and primitive type pointers behave exactly the same. Your code is wrong its that simple.
Reply With Quote  
Join Date: Feb 2005
Posts: 464
Reputation: winbatch is on a distinguished road 
Rep Power: 4
Solved Threads: 18
winbatch's Avatar
winbatch winbatch is offline Offline
Posting Pro in Training

Re: C++ Object Pointers Problem

  #3  
Sep 7th, 2005
(In other words, don't be confused by the * in char *, treat char * like int and it will be clear...)
Reply With Quote  
Reply

Only community members can participate in forum threads. You must register or log in to contribute.



Similar Threads
Other Threads in the C++ Forum
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)

 

Thread Tools Display Modes
Forums | Blogs | Tutorials | Code Snippets | Whitepapers | RSS Feeds | Advertising
All times are GMT -4. The time now is 7:28 am.
Newsletter Archive - Sitemap - Privacy Statement - Acceptable Use Policy - Contact Us
Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC