There is a big mistake in memory allocation. stackp is an automatic (stack) array, which means that its lifetime expires as soon as the insert returns. You must use a different distribution method. You can force the caller to allocate a new array and pass both pointers, or you can do it yourself with malloc (remember to free).
However, everything looks good. This is almost the only non-local insertion algorithm. You can do this a little faster with special tricks (for example, copying two ints at once). memmove and memcopy can use such optimizations on some architectures.
In addition, many algorithms will write stackp[index] when the position is found, and not at the end. But the basic algorithm is basically the same.
An alternative would be to insert in place (offset only elements after the insertion position) instead of using a new array. You often expand with realloc . This would be preferable in many situations, as it saves copying time and avoids the malloc new memory cell (which can also fragment the heap).
Finally, an alternative data structure is a fully linked list. This completely eliminates the need to copy items, but uses more memory and prevents accidental access.
source share