Dynamic array using ANSI C

后端 未结 3 637
暗喜
暗喜 2020-12-04 01:05

I have a char array

char *data[]= {\"11\", \"22\", \"33\", \"44\", \"55\"};

How can I add some extra items to it in the end? data[]=\

3条回答
  •  感动是毒
    2020-12-04 01:30

    Here is a macro based solution for a dynamic array in C with a very nice syntax to use. Works for any data type.

    #include 
    #include 
    #include 
    
    int main()
    {
      int* elems = NULL; /* Initialize a dynamic array. */
      W_DYNAMIC_ARRAY_PUSH(elems, 1, 2, 3, 4); /* Push some elements. */
    
      /* Iterate all elements. */
      W_DYNAMIC_ARRAY_FOR_EACH(int, e, elems) {
        printf("%d\n", e);
      }
    
      W_DYNAMIC_ARRAY_FREE(elems); /* Free the array only this way since there is a hidden header. */
    }
    

    The library uses Boost pre-processor library so Boost library needs to be there at build time.

提交回复
热议问题