Insert/Erase in C array
Last updated on
If you are in C land you might want an array you can insert and remove data from, this is a quick way todo that, this doesn’t handle resizing the memory or different types, but its easy to see how you would do that.
Essentually you are shuffeling the data up or down at a point.
#include <stdio.h>
#include <string.h>
#define D_COUNT 16
int data[D_COUNT];
void
insert_data(int idx, int new_data) {
int i;
int bytes = sizeof(data[0]) * (D_COUNT - idx - 1);
memmove(&data[idx + 1], &data[idx], bytes);
data[idx] = new_data;
for(i = 0; i < D_COUNT; ++i) {
printf("%d, ", data[i]);
}
printf("\n");
}
void
erase_data(int idx) {
int i;
int bytes = sizeof(data[0]) * (D_COUNT - idx - 1);
memmove(&data[idx], &data[idx + 1], bytes);
for(i = 0; i < D_COUNT; ++i) {
printf("%d, ", data[i]);
}
printf("\n");
}
int
main() {
int i;
int new_data;
int bytes;
memset(data, 0, sizeof(data));
/* create some data */
for(i = 0; i < D_COUNT; ++i) {
data[i] = i + 1;
}
for(i = 0; i < D_COUNT; ++i) {
printf("%d, ", data[i]);
}
printf("\n");
/* insert some data */
insert_data(0, 0);
insert_data(D_COUNT / 2, 123);
insert_data(D_COUNT - 1, 546);
/* remove data */
erase_data(D_COUNT - 1);
erase_data(D_COUNT / 2);
erase_data(0);
return 0;
}
Well the answer depends on the language.
Compile and Run in C
cc insert_remove.c && ./a.out
Outputs
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
0, 1, 2, 3, 4, 5, 6, 7, 123, 8, 9, 10, 11, 12, 13, 14,
0, 1, 2, 3, 4, 5, 6, 7, 123, 8, 9, 10, 11, 12, 13, 546,
0, 1, 2, 3, 4, 5, 6, 7, 123, 8, 9, 10, 11, 12, 13, 546,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 546, 546,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 546, 546, 546,
You can see the last number getting duplicated because the contents of the array are shuffeling down.