dynamicArray

general purpose dynamic array for one element type
git clone https://noulin.net/git/dynamicArray.git
Log | Files | Refs | README | LICENSE

main.c (1909B)


      1 #include "libdarray.h"
      2 #include <stdio.h>
      3 #include <inttypes.h>
      4 
      5 // element type for the myDynt dynamic array
      6 typedef struct  {
      7     uint32_t a,b;
      8 } elementt;
      9 
     10 
     11 // dynamic array of int elements
     12 dArrayT(intDynt, int);
     13 
     14 // dynamic array of elementt elements
     15 dArrayT(myDynt, elementt);
     16 
     17 
     18 int main(int ARGC, char** ARGV) {
     19 
     20   // EXAMPLE 1
     21 
     22   // dynamic array of int elements
     23   intDynt a;
     24 
     25   // the size of the dynamic array depends on dArrayAddrSpace and dArrayBaseBits in libdarray.h
     26   printf("sizeof intDyn: %d\n", sizeof a);
     27 
     28   // initialize a (malloc first buffer)
     29   dArrayInit(&a);
     30 
     31   // current maxCount for a
     32   printf("max %"PRIiMAX"\n", a.maxCount);
     33 
     34   // add elements
     35   dArrayPush(&a, 1);
     36   dArrayPush(&a, 2);
     37 
     38   // set value
     39   dArrayAt(&a, 1) = 3;
     40 
     41   // get value
     42   printf("get %"PRIi32"\n", dArrayAt(&a, 0));
     43 
     44   // pop an element
     45   printf("pop %"PRIi32"\n", dArrayPop(&a));
     46 
     47 
     48   // free the internal buffers in a
     49   dArrayFree(&a);
     50 
     51 
     52   // EXAMPLE 2
     53 
     54   // dynamic array of elementt elements
     55   myDynt b;
     56 
     57   // the size of the dynamic array depends on dArrayAddrSpace and dArrayBaseBits in libdarray.h
     58   printf("\n\nsizeof myDyn: %d\n", sizeof b);
     59 
     60   // initialize b of size at least 17
     61   dArrayInitCount(&b, 17);
     62 
     63   // current maxCount for a
     64   printf("max %"PRIiMAX"\n\n", b.maxCount);
     65 
     66   // local elements
     67   typeof(b.element) dta;
     68 
     69   dta.a = 123;
     70   dta.b = 2018;
     71 
     72   for(int i = 0; i < 1+(1<<2); i++) {
     73       dta.a += i;
     74       dArrayPush(&b, dta);
     75       printf("index        %"PRIi32"\n", i);
     76       printf("maxcount     %"PRIiMAX"\n", a.maxCount);
     77       printf("get e.a      %"PRIi32"\n", dArrayAt(&b, i).a);
     78       dArrayAt(&b, i).a -= i-1;
     79       printf("modified e.a %"PRIi32"\n", dArrayAt(&b, i).a);
     80       printf("get e.b      %"PRIi32"\n", dArrayAt(&b, i).b);
     81   }
     82 
     83   // get first element
     84   printf("\nget e(0).a   %"PRIi32"\n", dArrayAt(&b, 0).a);
     85 
     86   // free the internal buffers in b
     87   dArrayFree(&b);
     88 }