RSS Forums RSS
Please support our C++ advertiser: Programming Forums

Passing char * to function and populating inside

Join Date: Sep 2004
Posts: 6,576
Reputation: Narue has much to be proud of Narue has much to be proud of Narue has much to be proud of Narue has much to be proud of Narue has much to be proud of Narue has much to be proud of Narue has much to be proud of Narue has much to be proud of Narue has much to be proud of Narue has much to be proud of 
Rep Power: 31
Solved Threads: 499
Super Moderator
Narue's Avatar
Narue Narue is offline Offline
Expert Meanie

Re: Passing char * to function and populating inside

  #4  
Jul 27th, 2005
fillMe is a copy of the pointer, so you're allocating memory to a copy, then the copy is destroyed, thus destroying your only reference to the memory. This is affectionately called a memory leak. The solution in C is to pass a pointer to the pointer so that you can get to the original object:
#include <cstring>
#include <iostream>

using namespace std;

void test( char ** fillMe )
{
  *fillMe = new char[10];
  strcpy( *fillMe, "TESTING" );
}

int main()
{
  char * tester = NULL;

  test( &tester );

  if ( tester == NULL )
  {
    cout<< "tester is null"<<endl;
  }
  else
    cout<< tester <<endl;
}
Notice that I included <cstring>, which is required for memset and strcpy, and I also removed memset because there's no point in using it since you'll just use strcpy right after.

The C++ version using references is even easier:
#include <cstring>
#include <iostream>

using namespace std;

void test( char *& fillMe )
{
  fillMe = new char[10];
  strcpy( fillMe, "TESTING" );
}

int main()
{
  char * tester = NULL;

  test( tester );

  if ( tester == NULL )
  {
    cout<< "tester is null"<<endl;
  }
  else
    cout<< tester <<endl;
}
If I might direct you here, you'll probably have an easier time with pointers.
I'm here to prove you wrong.
Reply With Quote  
Forums | Blogs | Tutorials | Code Snippets | Whitepapers | RSS Feeds | Advertising
All times are GMT -4. The time now is 12:14 am.
Newsletter Archive - Sitemap - Privacy Statement - Acceptable Use Policy - Contact Us
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC