-4
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

void insertion_sort(int arr[]);

void insertion_sort(int arr[]) {

    int hold;
    int key;

    for (int i = 2; i < 7; i++) {
        key = arr[i];
        hold = i- 1;
        while (hold >= 0 && arr[hold] > key) {
            arr[hold + 1] = arr[hold];
            hold--;
        }
        arr[hold + 1] = key;
    }

}


int main() {


    int arr[] = {3,4,5,6,7,1,4};

    insertion_sort(arr);

    for (int i = 0; i < sizeof(arr) / sizeof(int); i++) {
        printf("%d", arr[i]);
    }

    return 0;
}

It seems like I cannot use [ sizeof(arr) / sizeof(int) ] in order to get the length of the array in insertion_sort. So I used the integer number instead. What is the reason and what's the proper way of manipulating the array that's taken as a parameter of a function??

0

2 Answers 2

2

You cannot get the array size inside a function.

What you do instead is to pass the size as another parameter.

void insertion_sort(int arr[], int size)
Sign up to request clarification or add additional context in comments.

Comments

2

You can't find the size of an array from inside the function. In the call, the array decays into a pointer to the first element, and clearly a pointer has no concept of how much data it points at in terms of number of elements.

This is simply how C works.

You should add a second argument to indicate the length, and make it have type size_t since that type conveys that we're talking about a size.

See, for instance, the standard library's qsort() function:

void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));

Basically base and nmemb describe an array.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.