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!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <cstring>
#include <conio.h>
#include <string.h>
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 "<<i+1<<":";
		cin>>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<<a[i]<<";";
	cout<<endl;
	system("pause");//
	return 0;
}
Line 8 and 9. You are discarding everything in your array and pointing to a new space in memory.
1
2
3
4
5
6
7
8
9
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.
1
2
3
4
5
6
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.