Size of a compound literal array

  • Thread starter Christopher Collins
  • Start date
C

Christopher Collins

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
 
E

Eric Sosman

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?

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.
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,533
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top