Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice to split a C array by simply using a pointer to the middle of it?

I am implementing a version of merge sort in c. For the first step I have to split the array into sub-arrays.

Is it bad practice to simply do this by having two pointers, one pointing to the start of the original array and the second pointing to the middle?

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

like image 723
Shane Avatar asked Feb 17 '12 13:02

Shane


3 Answers

I don't think it's bad practice if you know what you're doing. In some cases, you sacrifice readability for efficiency. It's probably more clear if you'd just create two more arrays, but if you have a firm grasp on arrays and pointers, why allocate extra memory?

like image 154
Luchian Grigore Avatar answered Sep 22 '22 14:09

Luchian Grigore


Absolutely not! The whole point of programming in C is being able to do these neat pointer tricks!

Do note, however, that mergesort is not inplace so you will still need to malloc an auxiliary array. If you do the correct pointer tricks you can just malloc once and reuse it though.

like image 42
hugomg Avatar answered Sep 18 '22 14:09

hugomg


It's just fine to use one array in such case (as merge sort). Calling malloc is unnecessary, unless the size of the array is too big for the stack.

like image 41
MByD Avatar answered Sep 19 '22 14:09

MByD