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
{
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