Size of a compound literal array

Discussion in 'C Programming' started by Christopher Collins, Sep 12, 2013.

  1. int main(void)
    {
    struct foo {
    short *vals;
    int num_vals;
    };

    struct foo myfoo = {
    .vals = (short[]) { 1, 2, 3 },
    .num_vals = 3,
    };

    return 0;
    }

    My question relates to the initialization of num_vals. The above code
    requires the programmer to manually count the number of elements pointed
    to by vals, which is less than desirable.

    Counting the size of the array seems like something the computer should
    be doing, but I can't figure out how to make it do that. Applying
    sizeof to vals doesn't work, since vals is a pointer, not an array. The
    only solution I could come up with is to place a sentinel value (e.g.,
    -1) at the end of the array, and then write code to count the number of
    elements at runtime. I am not too pleased with this solution for a
    number of reasons, but mostly just on the principle that I shouldn't be
    doing something at runtime that can be done during compilation.

    Any ideas?

    Thanks, Christopher
     
    Christopher Collins, Sep 12, 2013
    #1
    1. Advertisements

  2. Christopher Collins

    Eric Sosman Guest

    The obvious idea is to abandon the compound literal:

    short myfoo_vals[] = { 1, 2, 3, };
    struct foo myfoo = {
    .vals = myfoo_vals,
    .num_vals = sizeof myfoo_vals / sizeof myfoo_vals[0],
    };

    Conveniences are not guaranteed convenient in all circumstances.
     
    Eric Sosman, Sep 12, 2013
    #2
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.