Problem with my Array

Hi everbody, I wanted to know, I made a little program that pick a word from a text file than pass the word into a Suffle letters function end then sending me back the result to Main,

string sword ()

{
char* Sdword = NULL;
string Sword = pword();
int word_s = Sword.size();
Sdword = new char[word_s] ;
int word_counter = 0;
srand(time(0));


while (word_counter != word_s)

{
int random = rand() % Sword.size() ;
Sdword[word_counter]= Sword [random];
Sword.erase(random,1);
++word_counter;

}

return Sdword;

}

the Problem is whenever a pick a long word in my dictionary ( about 6 characters or more), it start to add more Characters throught the real shuffled word, like weird accent, capital letters and ASCII weird signs ( all my words are written in normal letters type), I tried a couple time to clear my entire array before each use but in vain.

Last edited on
Doesn't your compiler comment how you return a char* from function whose return type is std::string?

Who does deallocate that dynamically allocated array?


You already have a std::string Sword. Shuffle it.
http://www.cplusplus.com/reference/algorithm/shuffle/

No additional memory required.
The weird characters are because there is no null terminator on the c-string. The buffer needs to be longer by one character, and place a zero '\0' in the last position. But do take heed of the other issues, using new without delete gives a memory leak. Better to use std::string instead.

Try replacing
 
    char* Sdword = new char[word_s];
with
 
    std::string Sdword = std::string(word_s, 0);


Also, make sure the program doesn't call srand() more than once.
In my case I also got my function pword() who s picking a random line in a text file , so when you say to make sure to not call srand () more than once are you talking about calling this statement across many function or calling it once in a specified function
When I mentioned srand() it was a general comment, I wasn't sure of the context.
Usually it is called just once in the entire program, at the start of main().

If the function sword () is called more than once, then the random number generator will be re-seeded each time which makes the numbers less random.
Thanks by the way it worked pretty well!!
Topic archived. No new replies allowed.