2

I'm new to C programming and wonder if there is a way to prevent changing the values of an array.

I have an array:

int *array = makeArray();

Then I apply a sorting method to this array:

sortingMethod1(array);

When I call:

sortingMethod2(array);

The list is already sorted and I have no way of benchmarking the second sorting method.

I'd like to know if there is a way of passing the same array to both functions without sorting it for the next function.

If anyone could help me with what seems to be a very simple question I would appreciate it.

2
  • How is the array created? Via malloc()? Does it just return a static variable? Commented Apr 27, 2016 at 20:15
  • Already got the answer i was looking for, but it was created with malloc and it returns an (array) variable of random size, with random ints Commented Apr 27, 2016 at 20:21

2 Answers 2

5

If the sorting methods sort the array in-place, you will need to send them a copy of the array. To avoid code duplication, the copying is best extracted into a utility function:

void benchmark(int *array, size_t array_len, void (*method)(int *)) {
    int *array_copy = malloc(array_len * sizeof(int));
    memcpy(array_copy, array, array_len * sizeof(int));

    /* you can initialize a timer here */
    method(array_copy);
    /* you can output elapsed time here */

    free(array_copy);
}

// ...
int *array = makeArray();
benchmark(array, array_len, sortingMethod1);
benchmark(array, array_len, sortingMethod2);
Sign up to request clarification or add additional context in comments.

2 Comments

Well that was a quick answer, exactly what i was looking for. Thanks!
@tester please "accept" the best answer you like. That's how SO works!
2

You could copy the array as suggested. An alternative is to create an additional array of pointers, each spot pointing to the data in the original array. When sorting you look at the data being pointed to but change the location of the pointer instead of the data itself. Would probably be more efficient in terms of memory.

I am not aware of a way to sort an array without mutating it without using some sort of copy, be it the data or pointers to it. In C an array is very similar to a pointer to memory .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.