Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>They would start by hiding the defining a structure that would hold members necessary for the implementation. Then providing a group of functions that would manipulate the contents of the structure.</p> <p>Something like this:</p> <pre><code>typedef struct vec { unsigned char* _mem; unsigned long _elems; unsigned long _elemsize; unsigned long _capelems; unsigned long _reserve; }; vec* vec_new(unsigned long elemsize) { vec* pvec = (vec*)malloc(sizeof(vec)); pvec-&gt;_reserve = 10; pvec-&gt;_capelems = pvec-&gt;_reserve; pvec-&gt;_elemsize = elemsize; pvec-&gt;_elems = 0; pvec-&gt;_mem = (unsigned char*)malloc(pvec-&gt;_capelems * pvec-&gt;_elemsize); return pvec; } void vec_delete(vec* pvec) { free(pvec-&gt;_mem); free(pvec); } void vec_grow(vec* pvec) { unsigned char* mem = (unsigned char*)malloc((pvec-&gt;_capelems + pvec-&gt;_reserve) * pvec-&gt;_elemsize); memcpy(mem, pvec-&gt;_mem, pvec-&gt;_elems * pvec-&gt;_elemsize); free(pvec-&gt;_mem); pvec-&gt;_mem = mem; pvec-&gt;_capelems += pvec-&gt;_reserve; } void vec_push_back(vec* pvec, void* data, unsigned long elemsize) { assert(elemsize == pvec-&gt;_elemsize); if (pvec-&gt;_elems == pvec-&gt;_capelems) { vec_grow(pvec); } memcpy(pvec-&gt;_mem + (pvec-&gt;_elems * pvec-&gt;_elemsize), (unsigned char*)data, pvec-&gt;_elemsize); pvec-&gt;_elems++; } unsigned long vec_length(vec* pvec) { return pvec-&gt;_elems; } void* vec_get(vec* pvec, unsigned long index) { assert(index &lt; pvec-&gt;_elems); return (void*)(pvec-&gt;_mem + (index * pvec-&gt;_elemsize)); } void vec_copy_item(vec* pvec, void* dest, unsigned long index) { memcpy(dest, vec_get(pvec, index), pvec-&gt;_elemsize); } void playwithvec() { vec* pvec = vec_new(sizeof(int)); for (int val = 0; val &lt; 1000; val += 10) { vec_push_back(pvec, &amp;val, sizeof(val)); } for (unsigned long index = (int)vec_length(pvec) - 1; (int)index &gt;= 0; index--) { int val; vec_copy_item(pvec, &amp;val, index); printf("vec(%d) = %d\n", index, val); } vec_delete(pvec); } </code></pre> <p>Further to this they would achieve encapsulation by using void* in the place of vec* for the function group, and actually hide the structure definition from the user by defining it within the C module containing the group of functions rather than the header. Also they would hide the functions that you would consider to be private, by leaving them out from the header and simply prototyping them only in the C module.</p>
 

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