c - Optimal array push -


i wanna create function taking 2 parameters: int element, , input array. want function place element parameter @ first place in array, enlarge array single index, , place input array after pushed element.

to illustrate this, let's input array {1, 2, 3}, , element passed parameter 5. output should {5, 1, 2, 3}.

how can optimally?

i came out function:

void push(int el, int **arr) {     int *arr_temp = *arr;      *arr = null;     *arr = (int*) malloc(sizeof(int)*(n - 1));      (*arr)[0] = el;     for(int = 0; < (int)n - 1; i++)     {         (*arr)[i + 1] = arr_temp[i];     } } 

it works, well, it's not fastest function wrote, , slows down whole program. there better way this?

my guess doing (*arr)[1] = arr_temp, didn't work, , i'm not sure if there's possibility in c this.

instead of using raw array, it'd better wrap array in struct:

typedef struct {     size_t elementsallocated;     size_t elementsused;     int* buffer; } vector; 

and pushing function like:

vector* push_front(vector* v, int item) {     if (elementsused == elementsallocated)     {         // time grow buffer.         int elementsallocated = v->elementsallocated * 2;         if (elementsallocated <= v->elementsallocated)         {             abort(); // overflow occurred.         }          int* buffer = realloc(v->buffer, elementsallocated * sizeof *buffer);         if (buffer == null)         {             abort();         }          // shift existing data over.         memmove(buffer + elementsallocated - v->elementsused,                 buffer + v->elementsallocated - v->elementsused,                 v->elementsused * sizeof *buffer);         v->buffer = buffer;         v->elementsallocated = elementsallocated;     }      // prepend new item.     int* p = v->buffer + v->elementsallocated - v->elementsused - 1;     *p = item;     v->elementsused++;     return p; } 

this simpler if can append items end of array instead of prepending beginning. note above code untested , may contain off-by-one errors, core ideas are:

  • memory allocation expensive. allocate more memory need , write allocated unused space. reduces number of times need reallocate buffer , copy data shift over.
  • minimize number of times have grow buffer growing in larger steps.

Comments

Popular posts from this blog

android - getbluetoothservice() called with no bluetoothmanagercallback -

sql - ASP.NET SqlDataSource, like on SelectCommand -

ios - Undefined symbols for architecture armv7: "_OBJC_CLASS_$_SSZipArchive" -