I have been trying to implement a quick sort of array of arrays of chars in C but it's giving me a segmentation fault error that I am not able to debug. This is the code:
int partition(char **a, int left, int right)
{
int i, j;
char pivot[16];
strcpy(pivot, a[left]);
i = left;
j = right + 1;
while (1)
{
do
i++;
while (i <= right && strcmp(a[i], pivot) < 0);
do
j--;
while (strcmp(a[j], pivot) > 0);
if (i >= j)
break;
char t[16];
strcpy(t, a[i]);
strcpy(a[i], a[j]);
strcpy(a[j], t);
}
char t[16];
strcpy(t, a[left]);
strcpy(a[left], a[j]);
strcpy(a[j], t);
return j;
}
void quickSortChar(char **a, int left, int right)
{
int j;
if (left < right)
{
j = partition(a, left, right);
quickSortChar(a, left, j - 1);
quickSortChar(a, j + 1, right);
}
}
int main()
{
char **arr = (char **)calloc(10, sizeof(char *));
arr[0] = (char *)malloc(16);
arr[1] = (char *)malloc(16);
arr[2] = (char *)malloc(16);
arr[0] = "patata";
arr[1] = "berenjena";
arr[2] = "alioli";
quickSortChar(arr, 0, 2);
}
Update 1
Using strcpy does not work either:
int partition(char **a, int left, int right)
{
int i, j;
char pivot[16];
strcpy(pivot, a[left]);
i = left;
j = right + 1;
while (1)
{
do
i++;
while (strcmp(a[i], pivot) < 0 && i <= right);
do
j--;
while (strcmp(a[j], pivot) > 0);
if (i >= j)
break;
char t[16];
strcpy(t, a[i]);
strcpy(a[i], a[j]);
strcpy(a[j], t);
}
char t[16];
strcpy(t, a[left]);
strcpy(a[left], a[j]);
strcpy(a[j], t);
return j;
}
Update 2
I have solved the warning by moving up the declaration.
Update 3
Fix while (i <= right && strcmp(a[i], pivot) < 0);
strcpy()to copy a string. Thearr[0] = "patata";etc overwrites the pointers that you allocated.partition()or move the function. Don't ignore compiler warnings.malloc:char *arr[] = { "patata", "berenjena", "alioli" };, and you certainly don't needstrcpy.