Feb 1, 2010 at 12:22pm UTC
#include <iostream.h>
#include <string.h>
#include <stdlib.h>
void bubblesort(char *name[], int size);
void display (char*name[],int size);
int main()
{
int i, size;
char temp[80];
char **name;
cout<<"Please enter the number of names you want to enter = ";
cin>>size;
cin.ignore(3,'\n');
cout<<endl;
name = new char *[size];
for (i = 0; i<size; i++)
{
cout<<"Please enter name "<<i+1<<": ";
cin.getline(temp,80,'\n');
name[i]=new char[strlen(temp)+1];
strcpy(name[i],temp);
}
cout<<endl;
display(name,size);
bubblesort(name,size);
system("cls");
display(name,size);
system("pause");
return 0;
}
void bubblesort(char *name[], int size)
{
int i,sort = 0;
char temp[80];
do
{
for(i =0; i<size; i++)
{
if ( strcmp(name[i],name[i+1]) >0 )
{
strcpy(temp, name[i]);
strcpy(name[i],name[i+1]);
strcpy(name[i+1],temp);
sort++;
}
}
}while(sort!=0);
}
void display (char* name[],int size)
{
for (int i = 0; i<size; i++)
{
cout<<"Name "<<i+1<<" : "<<name[i]<<endl;
}
}
No error when compile and execute. but program crashed when passing through bubble sort function.
Feb 1, 2010 at 12:52pm UTC
It could be that is because of "i<size".
Few lines below you use [i+1] so on the last loop i+1 is not < size.
You are accessing uninitialized pointer.
Make it "i<size-1"
Feb 1, 2010 at 12:53pm UTC
In your for inside the do while, i will at one point ==size. At that point, during strcmp(), you'll be dereferencing name[i+1], causing a segmentation fault.
Feb 1, 2010 at 1:18pm UTC
for (i =0; i<size-1; i++)
and
while (sort!=0,sort=0);
Last edited on Feb 1, 2010 at 1:18pm UTC
Feb 1, 2010 at 1:31pm UTC
ermm, if i put i<size-1, then my last name will not be sorted
Feb 1, 2010 at 1:44pm UTC
okay. i made the change, but the names are still not sorted. the program just stopped when it display the names entered.
Feb 1, 2010 at 2:19pm UTC
oh my mistake again..
sort=0;
on top of for (i =0; i<size-1; i++)
then
while (sort!=0);
that should work now..
Feb 1, 2010 at 2:28pm UTC
OH great. It works.
thank a lot!
i made a really silly mistake. heehee. thanks a lot :DD