To insert a value into an array, you need to shift every value after the location you want to insert. This way you make a hole for the new value. Of course, this can be a problem if the array is already full. You would most likely end up throwing away the last value in the list. If that's acceptable then the logic is very simple: start from the end and copy the previous item to the current element until you hit the location you want to insert. A simple implementation might look like this:
#include <stdio.h>
#define length(x) (sizeof x / sizeof *x)
int insert(int *array, int val, size_t size, size_t at)
{
size_t i;
/* In range? */
if (at >= size)
return -1;
/* Shift elements to make a hole */
for (i = size - 1; i > at; i--)
array[i] = array[i - 1];
/* Insertion! */
array[at] = val;
return 0;
}
int main(void)
{
int a[11] = {0,1,2,3,4,5,6,7,8,9};
int i;
if (insert(a, 6, length(a), 3) != -1) {
for (i = 0; i < length(a); i++)
printf("%-3d", a[i]);
printf("\n");
}
else
fprintf(stderr, "Insertion failed\n");
return 0;
} Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401