cwindowsalgorithmsortinglcc-win32

Insertion Sort Doing Nothing


I wrote the following insertion sort yesterday (I started learning C 3 days ago). For some reason, the sort does not modify the array AT ALL.

#include <stdio.h>
int *insert(int arr[], int index, int item);
int *isort(int arr[]);
int main() {
    int a[17] = {1, 2, 9, 5, 3, 2, 1, 6, 5, 9, 0, 1, 3, 4, 2, 3, 4};
    int *b = isort(a);
    for (int i = 0; i < 17; i += 1) {
        printf("%d ", b[i]);
    }
    return 0;
}
int *insert(int arr[], int index, int item) {
    --index;
    while (index >= 0 && item < arr[index]) {
        arr[index + 1] = arr[index];
        --index;
    }
    arr[index + 1] = item;
    return arr;
}
int *isort(int arr[]) {
    for (int i = 1; i < sizeof(arr) - 1; i++) {
        arr = insert(arr, i, arr[i]);
    }
    return arr;
}

I'm thinking it could be my compiler, as I'm running a compiler that is on a non unix machine: lcc-win, but I'm not sure. Is there some fundamental thing I'm missing here?


Solution

  • int *isort(int arr[]) {
        for (int i = 1; i < sizeof(arr) - 1; i++) {
            arr = insert(arr, i, arr[i]);
        }
        return arr;
    }
    

    In this function sizeof(arr) actually returns the size of the pointer and not the size of the array.

    In C a special rule says an array parameter is actually adjusted to a parameter of the corresponding pointer type.

    That is:

    int *isort(int arr[]) { /* ... */ }
    

    is equivalent to this:

    int *isort(int *arr) { /* ... */ }
    

    To fix this, add a new parameter in your function that takes the size of the array:

    int *isort(int arr[], size_t size) { /* ... */ }