Assign multiple values to array in C

前端 未结 8 1281
无人共我
无人共我 2020-12-01 14:01

Is there any way to do this in a condensed form?

GLfloat coordinates[8];
...
coordinates[0] = 1.0f;
coordinates[1] = 0.0f;
coordinates[2] = 1.0f;
coordinates         


        
8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-01 14:13

    With code like this:

    const int node_ct = 8;
    const int expected[node_ct] = { 1, 3, 4, 2, 5, 6, 7, 8 };
    

    And in the configure.ac

    AC_PROG_CC_C99
    

    The compiler on my dev box was happy. The compiler on the server complained with:

    error: variable-sized object may not be initialized
       const int expected[node_ct] = { 1, 3, 4, 2, 5, 6, 7, 8 };
    

    and

    warning: excess elements in array initializer
       const int expected[node_ct] = { 1, 3, 4, 2, 5, 6, 7, 8 };
    

    for each element

    It doesn't complain at all about, for example:

    int expected[] = { 1, 2, 3, 4, 5 };
    

    however, I decided that I like the check on size.

    Rather than fighting, I went with a varargs initializer:

    #include 
    
    void int_array_init(int *a, const int ct, ...) {
      va_list args;
      va_start(args, ct);
      for(int i = 0; i < ct; ++i) {
        a[i] = va_arg(args, int);
      }
      va_end(args);
    }
    

    called like,

    const int node_ct = 8;
    int expected[node_ct];
    int_array_init(expected, node_ct, 1, 3, 4, 2, 5, 6, 7, 8);
    

    As such, the varargs support is more robust than the support for the array initializer.

    Someone might be able to do something like this in a macro.

    Find PR with sample code at https://github.com/wbreeze/davenport/pull/15/files

    Regarding https://stackoverflow.com/a/3535455/608359 from @paxdiablo, I liked it; but, felt insecure about having the number of times the initializaion pointer advances synchronized with the number of elements allocated to the array. Worst case, the initializing pointer moves beyond the allocated length. As such, the diff in the PR contains,

      int expected[node_ct];
    - int *p = expected;
    - *p++ = 1; *p++ = 2; *p++ = 3; *p++ = 4;
    + int_array_init(expected, node_ct, 1, 2, 3, 4);
    

    The int_array_init method will safely assign junk if the number of arguments is fewer than the node_ct. The junk assignment ought to be easier to catch and debug.

提交回复
热议问题