Skip to content

Instantly share code, notes, and snippets.

@ereidland
Created April 13, 2013 16:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ereidland/5379184 to your computer and use it in GitHub Desktop.
Save ereidland/5379184 to your computer and use it in GitHub Desktop.
Example 6 at Library.
#include <iostream>
using namespace std;
char * myFunction(const char * str)
{
//Declare the fixed size array of 32 ize.
char fixedSizeArray[32];
//Copy str into it.
strcpy(fixedSizeArray, str);
//Return it.
return fixedSizeArray;
//Althout it does not result in a compiler error, it fails because it's returning the address of temporary data (myFixedArray)
}
char * myGoodFunction(const char * str)
{
//In order to make it work:
//Declare new pointer, and initialize it to a new character array of 32 size.
char * dynamicArray = new char[32];
//Copy str into it.
strcpy(dynamicArray, str);
//Return it.
return dynamicArray;
//Note that if we do not keep track of the returned data, it results in a memory leak (since a new object was dynamically created.)
}
void main()
{
//Print result of myFunction with "Teeeeesting!" as the argument.
cout << myFunction("Teeeeesting!") << endl;
//Get result of myGoodFunction with "Teeeeesting!" as the argument.
//Needs to be done to avoid a memory leak.
char * result = myGoodFunction("Teeeeesting!");
//Print out result.
cout << result << endl;
//Delete result. For deleting an array, delete requires the empty [].
//Otherwise delete things it's just getting a pointer to a single item, rather than array.
//So if [] was left off, it would assume that it was only getting a pointer to the first character in result.
delete [] result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment