Getting number of elements in array not working as expected

128 Views Asked by At

Here I am implementing a simple sort (insertion), but I'm not getting the correct size of the array. Namely, my length variable is getting set equal to 1. Also, what ways could I optimize my code for this insertion sort algorithm? Thanks

void insertionSort(int a[])
{
    int sorted = 1;
    int length = sizeof(a) / sizeof(int);
    int i = 0;
    int tmp;

    printf("%d   ", length);

    if (length < 2)
        return;

    for (i = 1; i < length - 1; i++)
    {
        sorted = i;
        while (a[sorted] < a[sorted - 1] && sorted > 0)
        {
            tmp = a[sorted];
            a[sorted] = a[sorted - 1];
            a[sorted - 1] = tmp;
            sorted--;
        }
    }
}
2

There are 2 best solutions below

1
On
int length = sizeof(a) / sizeof(int);

This returns the size of a pointer a, divided by the size of an int. Always equal to one.

You will have to pass length to the function, void insertionSort(int a[], size_t length){

The function that creates the array has to keep track of the number of elements that are active in the array in order to do this.

0
On

C arrays doesn't really exists. This essentially means that you don't have good abstract support for arrays in C. As an example of this, if I give you (you are the function insertionSort) an array (say a) you won't be able to determine it size! Arrays have no size in C.

So what is sizeof(a)? First a is not an array but a constant pointer to the memory address of the first element; that's all. Then sizeof(a) just gives you the size of the pointer a.

If you want to manage arrays in C, you must use a variable to store its length. This is why most of functions that deals with arrays have additional parameters length.