Home > OS >  Quick sorting array of arrays of chars in C
Quick sorting array of arrays of chars in C

Time:12-20

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);

CodePudding user response:

Notice that you check i didn't passed the length of a only after strcmp(a[i], pivot) < 0 hence you reach i=3 and then get dumped.

Change to

while (i <= right && strcmp(a[i], pivot) < 0);

I'd also suggest using calloc instead of malloc in order to initialize the arr

  • Related