dimanche 21 mars 2021

My compiler keep showing an error for accessing memory I hav'ent allocated, what can I do to resolve it?

I'm Trying to make "Insertion sort Algorithm using heap memory through pointers". driver code:

    int* pointer_insertionsort = new int[ptrsize];
//copying pointer elements into this pointer for sorting
    for (int i = 0; i < ptrsize; i++)
    {
        pointer_insertionsort[i] = pointer[i];
    }

    cout << endl << endl;
    cout << "Orignal Array Before Insertion Sort = ";
    for (int i = 0; i < ptrsize; i++)
    {
        cout << pointer_insertionsort[i] << " ";
    }
    cout << endl;
    //sorting the coped array
    pointer_insertionsort = insertion_sort(pointer_bubsort, ptrsize);
    cout << "Sorted Array After Insertion Sort = ";
    for (int i = 0; i < ptrsize; i++)
    {
        cout << pointer_insertionsort[i] << " ";
    }
    cout << endl;

function code:

int* insertion_sort(int* ptr_is, int size)
{
    int count = 1;
    int temp;
    
        for (int j = 1; j < size; j++)
        {
            if (ptr_is[j] < ptr_is[j - 1])
            {
                for (int k=j; k>0; k--)
                {
                    if (ptr_is[k] < ptr_is[k - 1])
                    {
                        temp = ptr_is[k];
                        ptr_is[k] = ptr_is[k - 1];
                        ptr_is[k - 1] = temp;
                    }
                }
            }
        }
    return ptr_is;
}

why does it keep throwing the same error? do I have to change my code entirely or does this problem have a solution??

Aucun commentaire:

Enregistrer un commentaire