Skip to content

Instantly share code, notes, and snippets.

@Wollw
Created February 14, 2012 01:09
Show Gist options
  • Save Wollw/1822235 to your computer and use it in GitHub Desktop.
Save Wollw/1822235 to your computer and use it in GitHub Desktop.
insertion function example
#include <stdio.h>
/* This insertAt function takes an index to insert at "i",
* a number to insert into the integer array "num", a pointer
* to the current number of used spaces in the array "numUsed",
* and a pointer to the array "a".
*
* This assumes that the array is big enough to insert a new element
* for the sake of simplifying the example so it doesn't check against
* the number of allocated elements.
*
* The variable j never goes below zero as long as the index i
* we are trying to add at is greater than or equal to zero (which it
* certainly should be). This is because the for loop's condition
* is that it be greater than i and the only sane values for i are greater
* than or equal to 0. The loop copies all the values from index j-1
* to index j and once it sees that j is equal to i it exits the loop
* so it never has a chance to access the value at i-1. Once
* j is equal to i we only have to set a[j] (which is the same as a[i]
* as at this point i == j since that was essentially our exit condition)
* to num. We then remember to increment numUsed and return.
*/
void insertAt(size_t i, int num, size_t *numUsed, int a[]) {
size_t j;
for (j = *numUsed; j > i; j--) {
a[j] = a[j-1];
}
a[j] = num;
(*numUsed)++;
return;
}
int main() {
// Make a new array with 20 allocated
// set the first ten indices to 10 through 19
int a[20];
size_t i;
for (i = 0; i < 10; i++) {
a[i] = i+10;
}
// Only the first ten indices are in use.
size_t numUsed = 10;
// Add a few numbers to the array...
insertAt(0, 123, &numUsed, a);
insertAt(5, 456, &numUsed, a);
insertAt(9, 789, &numUsed, a);
for (i = 0; i < numUsed; i++)
printf("%d\t%d\n", i, a[i]);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment