944,030 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Unsolved
  • Views: 3841
  • C++ RSS
Sep 7th, 2005
0

C++ Object Pointers Problem

Expand Post »
Hi,

Please see the code below.

C++ Syntax (Toggle Plain Text)
  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

C++ Syntax (Toggle Plain Text)
  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.
Similar Threads
SpS
Reputation Points: 70
Solved Threads: 32
Posting Pro
SpS is offline Offline
598 posts
since Aug 2005
Sep 7th, 2005
0

Re: C++ Object Pointers Problem

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.
Reputation Points: 19
Solved Threads: 5
Junior Poster
Stoned_coder is offline Offline
164 posts
since Jul 2005
Sep 7th, 2005
0

Re: C++ Object Pointers Problem

(In other words, don't be confused by the * in char *, treat char * like int and it will be clear...)
Reputation Points: 68
Solved Threads: 18
Posting Pro in Training
winbatch is offline Offline
466 posts
since Feb 2005

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: substitute of sizeof operator
Next Thread in C++ Forum Timeline: how to open/run flash movies from c++





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC