### Having problems with the problem sorted in the order in the dictionary

Greetings!I have a problem with the problem sorted in dictionary order, hope you help!
 ``123456789101112131415161718192021222324252627282930313233343536373839404142`` ``````#include #include #include #include using namespace std; void HoanVi(char *a, char *b) { a = new char[20]; b = new char[20]; char *tmp = new char[20]; strcpy(tmp,a); strcpy(a,b); strcpy(b,tmp); } int main() { char *a[10];// 10 words in dictionary for(int i = 0; i<4;i++) { a[i] = new char[20]; cout<<"Input words "<>a[i]; cin.ignore(); } int min; for(int i = 0; i<4; i++) { min = i; for(int j = i+1; j < 4; j++) if(a[min]>a[j]) min = j; HoanVi(a[min], a[i]); } //after sorted for(int i = 0 ;i < 4; i++) cout<
Line 8 and 9. You are discarding everything in your array and pointing to a new space in memory.
 ``123456789`` ``````void HoanVi(char *a, char *b) { a = new char[20]; b = new char[20]; char *tmp = new char[20]; strcpy(tmp,a); strcpy(a,b); strcpy(b,tmp); }``````

That is wrong. The original arguments fed to the function are not modified to point to the new memory, so all memory allocated in this function is leaked. The original arguments already pointed to memory and there's no reason to allocate any in HoanVi.

Prefer to use strings.

Failing that, maybe something like the following.
 ``123456`` ``````void HoanVi(char *&a, char *&b) { char * tmp = a ; a = b ; b = temp ; }``````

There's no reason to copy what's pointed to when we can just swap the pointers.

Last edited on
Topic archived. No new replies allowed.