Joel
Joel

Reputation: 55

Bubble sort an Array of pointers of another arrays in a function (C)

I want to make a bubble sort function of an array of pointers that each of the pointers point to another arrays - inside of function and i'm getting a error that i violated a writing location (Visual Studio)

P.S, I do (*parr)++ because the first value of each array shows the length of the array without the first value so i need to start bubble sorting from the second box (arr[1] and not arr[0] for example ). can someone write to me how can i fix it? Thanks for help (I need to sort the values of the original arrays not the pointer of the arrays).

int main(void){

    int i = 0;
    int arr0[4] = { 3, 9, 6, 7 };
    int arr1[3] = { 2, 5, 5 };
    int arr2[1] = { 0 };
    int arr3[2] = { 1, 6 };
    int arr4[5] = { 4, 5, 6, 2, 1 };
    int* parr[5] = { arr0, arr1, arr2, arr3, arr4 };
    func1(parr);


    system("PAUSE");
    return (0);
}
void func1(int** parr)
{
    int i;
    int temp;
    int j;
    int k;
    int length;
    for (i = 0; i < 5; i++, (parr)++)
    {
        length = **parr;
        (*parr)++;
        for (j = 0; j < length-1; j++)
        {
            for (k = 0; k < length - j - 1; k++, (*parr)++)
            {
                if ((**parr)>(*(*parr + 1)))
                {
                    temp = **(parr);
                    **(parr) = (*(*parr + 1));
                    (*(*parr + 1)) = temp;
                }
            }
        }


    }


}

Upvotes: 2

Views: 301

Answers (1)

user3121023
user3121023

Reputation: 8286

This seems to work. It is easier in func1 to use dereferenceing as parr[i][k] rather than moving the pointer.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void func1(int** parr);

int main(void){
    int j;
    int arr0[4] = { 3, 9, 6, 7 };
    int arr1[3] = { 2, 5, 5 };
    int arr2[1] = { 0 };
    int arr3[2] = { 1, 6 };
    int arr4[5] = { 4, 5, 6, 2, 1 };
    int* parr[5] = { arr0, arr1, arr2, arr3, arr4 };
    func1(parr);
    for (j = 1; j <= arr0[0]; j++)
    {
        printf ( "arr0[%d] %d\n", j, arr0[j]);
    }
    for (j = 1; j <= arr4[0]; j++)
    {
        printf ( "arr4[%d] %d\n", j, arr4[j]);
    }
    return (0);
}

void func1(int** parr)
{
    int i;
    int temp;
    int j;
    int k;
    int length;
    for (i = 0; i < 5; i++)
    {
        length = **parr;

        for (j = 0; j < length; j++)
        {
            for (k = 1; k < length - j; k++)
            {
                temp = *((*parr)+k);
                if (*((*parr)+k)>*((*parr)+k+1))
                {
                    temp = *((*parr)+k);
                    *((*parr)+k) = *((*parr)+k+1);
                    *((*parr)+k+1) = temp;
                }
            }
        }
        *parr++;// next array
    }
}

Upvotes: 1

Related Questions