Initializing struct containing arrays
You may not initialize a scalar object like a pointer with a braced list that contains several initializers.
But you can use compound literals.
Here is a demonstrative program.
#include <stdio.h>
typedef struct curve {
float *xs;
float *ys;
int n;
} curve;
int main(void)
{
curve mycurve1 =
{
( float[] ){ 1, 2, 3 },
( float[] ){ 4, 2, 9 },
3
};
curve mycurve2 =
{
( float[] ){ 1, 2, 3, 4 },
( float[] ){ 0, 0.3, 0.9, 1.5 },
4
};
for ( int i = 0; i < mycurve1.n; i++ )
{
printf( "%.1f ", mycurve1.xs[i] );
}
putchar( '\n' );
for ( int i = 0; i < mycurve2.n; i++ )
{
printf( "%.1f ", mycurve2.ys[i] );
}
putchar( '\n' );
return 0;
}
Its output is
1.0 2.0 3.0
0.0 0.3 0.9 1.5
A suggested take on @Vlad from Moscow good answer.
Use const
when constant
because I know the array size at compile time and I don't need it to change during run-time.
Consider const curve mycurve1 = ...
. This allows for select optimizations, identifies mis-use and allows passing &mycurve1
to bar(const curve *)
. Also with const float [...
allows passing mycurve1.xs
to foo(const float *)
.
Avoid magic numbers
#define CURVE1_N 3
const curve mycurve1 = {
( const float[CURVE1_N] ){ 1, 2, 3 },
( const float[CURVE1_N] ){ 4, 2, 9 },
CURVE1_N
};