配列のサイズがこれ以上エントリに収まらない場合は、別の大きな配列を割り当て、すべてのエントリを新しいエントリが配置される位置まで移動し、そこにエントリを配置して、最後に残りのエントリを1つ上の位置に移動する必要があります。彼らよりも。その後、古いアレイと現在は小さすぎるアレイを解放して、新しいアレイを保持できます。あなたはそれを使うmemmove
かmemcpy
することができます。
これを行うには、新しい大きな配列を割り当てる必要がある場合、すぐに必要なものよりも少し大きく割り当てる必要があります(メモリページサイズの倍数が適切です)。そうしないと、すべての割り当てと解放にコストがかかります。
例:
int *array[] = malloc(3*sizeof(int));
array[0] = 0;
array[1] = 2;
array[2] = 3;
// To insert 1 for example you will have to do...
int *new_array[] = malloc(4*sizeof(int)); // Just for the example I make a tight fit, on the code you should allocate it a bit bigger if you expect more inserts to avoid unnecessary mallocs and frees
memmove(new_array,array,sizeof(int)); // Moving the 0
new_array[1] = 1; // Inserting the new element
memmove(new_array[2],array[1],2*sizeof(int)); // Moving the 2 and 3
free(array); // Get rid of the old array
array = new_array;
new_array = NULL;