C++ Object Pointers Problem

Please support our C++ advertiser: Intel Parallel Studio Home
Reply

Join Date: Aug 2005
Posts: 598
Reputation: SpS is on a distinguished road 
Solved Threads: 32
SpS's Avatar
SpS SpS is offline Offline
Posting Pro

C++ Object Pointers Problem

 
0
  #1
Sep 7th, 2005
Hi,

Please see the code below.

  1. void Allocate( char* s )
  2. {
  3. s = (char*)malloc( 100 );
  4. }
  5.  
  6. int main( )
  7. {
  8. char* s = NULL;
  9. Allocate( s );
  10. 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.*/
  11.  
  12. }

Now my question is

  1. void Allocate( Base* s )
  2. {
  3. s = new Base;
  4. }
  5.  
  6. int main( )
  7. {
  8. Base* obj = NULL;
  9. Allocate( obj );
  10. obj->some_member = 20; // this works...
  11.  
  12. }
<< 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.
Reply With Quote Quick reply to this message  
Join Date: Jul 2005
Posts: 164
Reputation: Stoned_coder is an unknown quantity at this point 
Solved Threads: 5
Stoned_coder Stoned_coder is offline Offline
Junior Poster

Re: C++ Object Pointers Problem

 
0
  #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 Quick reply to this message  
Join Date: Feb 2005
Posts: 466
Reputation: winbatch is on a distinguished road 
Solved Threads: 18
winbatch's Avatar
winbatch winbatch is offline Offline
Posting Pro in Training

Re: C++ Object Pointers Problem

 
0
  #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 Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the C++ Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC