Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>A lot of C projects end up implementing a vector-like API. Dynamic arrays are such a common need, that it's nice to abstract away the memory management as much as possible. A typical C implementation might look something like:</p> <pre><code>typedef struct dynamic_array_struct { int* data; size_t capacity; /* total capacity */ size_t size; /* number of elements in vector */ } vector; </code></pre> <p>Then they would have various API function calls which operate on the <code>vector</code>:</p> <pre><code>int vector_init(vector* v, size_t init_capacity) { v-&gt;data = malloc(init_capacity * sizeof(int)); if (!v-&gt;data) return -1; v-&gt;size = 0; v-&gt;capacity = init_capacity; return 0; /* success */ } </code></pre> <p>Then of course, you need functions for <code>push_back</code>, <code>insert</code>, <code>resize</code>, etc, which would call <code>realloc</code> if <code>size</code> exceeds <code>capacity</code>. </p> <pre><code>vector_resize(vector* v, size_t new_size); vector_push_back(vector* v, int element); </code></pre> <p>Usually, when a reallocation is needed, <code>capacity</code> is doubled to avoid reallocating all the time. This is usually the same strategy employed internally by <code>std::vector</code>, except typically <code>std::vector</code> won't call <code>realloc</code> because of C++ object construction/destruction. Rather, <code>std::vector</code> might allocate a new buffer, and then copy construct/move construct the objects (using placement <code>new</code>) into the new buffer.</p> <p>An actual vector implementation in C might use <code>void*</code> pointers as elements rather than <code>int</code>, so the code is more generic. Anyway, this sort of thing is implemented in a lot of C projects. See <a href="http://codingrecipes.com/implementation-of-a-vector-data-structure-in-c">http://codingrecipes.com/implementation-of-a-vector-data-structure-in-c</a> for an example vector implementation in C.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload