Is it a good practice to split an array of C just by using a pointer to the middle?

I am implementing a merge sort version in c. For the first step, I need to split the array into subarrays.

Is it wrong to do this if you have two pointers, one points to the beginning of the original array, and the second points to the middle?

Or should I malloc 2 new memory slots, copy the corresponding values ​​here, and then save a pointer to this space?

+8
c arrays pointers malloc
source share
5 answers

I don’t think this is bad practice if you know what you are doing. In some cases, you sacrifice readability for efficiency. Probably more understandable if you just create two more arrays, but if you have a clear understanding of arrays and pointers, why allocate extra memory?

+12
source share

Absolutely not! An entire C programming point can do these neat pointer tricks!

Note, however, that mergesort is not in place, so you will still need to malloc a helper array. If you do the right tricks with pointers, you can just malloc once and reuse it though.

+11
source share

It's just fine to use a single array in such a case (like merge sort). A malloc call is not needed if the size of the array is too large for the stack.

+2
source share

Typically, when sorting a merge, you want to put the result of the merge into the memory occupied by the original input. If so, then you should:

  • sort both halves
  • copy the "lower" half of your array into the newly allocated buffer, leave the "upper" half where it is
  • merges from the "upper" half and the additional buffer into the "lower part" of a large array.

Thus, you need to allocate as much additional memory as half the size of the input. You could even do this once at the beginning and reuse the same buffer as the workspace for all the merges you are about to do.

+2
source share

No, this is not bad, and in fact I would say that this is one of the only reasons for using C in the first place. If you are going to make wasteful copies of your data every time you need to process the same data in a slightly different way, you have already used one of the biggest expenses in languages ​​with a high level of script. You have also significantly increased the amount of error handling that your code should execute (since distribution may fail), and since error handling in C tends to be a bit β€œverbose” (to put it mildly), the cost of network complexity is much worse than the small complexity of accessing Subarema in place.

+1
source share

All Articles