Quantcast
Channel: Visual C forum
Viewing all articles
Browse latest Browse all 15302

How shall I handle these memory allocation in recursive function

$
0
0
// Word out all permutations of a given string.
	vector<char*> CppAlgorithms::permut(char s[], int length)
	{
		vector<char*> permutations;
		if(length == 1)
		{
			if(s[0] != ' ')
			{
				permutations.insert(permutations.begin(), s);
				return permutations;
			}
			else return permutations;
		}

		char firstChar = s[0];
		string remainder = string(s).substr(1);
		char * remainder_cstr = new char[length];
		strcpy_s(remainder_cstr, length, remainder.c_str());

		vector<char*> words = CppAlgorithms::permut(remainder_cstr, length-1);

		char *newWord = NULL;
		for(auto it = words.begin(); it<words.end(); ++it)
		{
			char *word = *it;
			for(int position = 0; position <= strlen(word); ++position)
			{
				// for each word, make it a modifiable string, stored in newWord;
				// insert "firstChar" into each position of word. "word" has 5 positions: [0-4]
				newWord = new char[strlen(word)+1];
				strcpy_s(newWord, strlen(word)+1, word);
				string *sNewWord = new string(newWord);
				(*sNewWord).insert(position, 1, firstChar);
				permutations.insert(permutations.begin(),1, const_cast<char*>((*sNewWord).c_str()));

			}
		}
		
		return permutations;
	}

Thanks in advance.


Remember to mark reply as answer if it answers the question.


Viewing all articles
Browse latest Browse all 15302

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>