[英]Initializing struct containing arrays
I have a struct in C, which members are float arrays.我在 C 中有一个结构,其中成员是浮点数组。 I want to initialize it during compile time like this:
我想在编译时像这样初始化它:
typedef struct curve {
float *xs;
float *ys;
int n;
} curve;
curve mycurve1 = {
{1, 2, 3},
{4, 2, 9},
3
};
curve mycurve2 = {
{1, 2, 3, 4},
{0, 0.3, 0.9, 1.5},
4
};
But I get compile errors.但我收到编译错误。
One possible solution might be to use arrays and not pointers in the struct.一种可能的解决方案可能是在结构中使用数组而不是指针。 This is the accepted answer of a very similar question from here: https://stackoverflow.com/a/17250527/1291302 , but the problem with that approach is that I don't know the array size at typedef time.
这是这里一个非常相似的问题的公认答案: https : //stackoverflow.com/a/17250527/1291302 ,但这种方法的问题是我不知道 typedef 时的数组大小。 Not only that, I might want to initialize another, bigger curve.
不仅如此,我可能还想初始化另一个更大的曲线。
Another approach might be with malloc, but I find that overkill, because I know the array size at compile time and I don't need it to change during run-time.另一种方法可能是使用 malloc,但我发现这有点矫枉过正,因为我在编译时知道数组大小,而且我不需要在运行时更改它。
I don't know another approaches, which might be useful.我不知道其他可能有用的方法。 Maybe casting array to pointer??
也许将数组转换为指针? - I don't really know how I would approach that.
- 我真的不知道我会如何处理。
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.来自莫斯科的对@Vlad的建议是一个很好的答案。
Use const
when constant const
时使用const
because I know the array size at compile time and I don't need it to change during run-time.
因为我在编译时知道数组大小,并且我不需要在运行时更改它。
Consider const curve mycurve1 = ...
.考虑
const curve mycurve1 = ...
。 This allows for select optimizations, identifies mis-use and allows passing &mycurve1
to bar(const curve *)
.这允许选择优化,识别误用并允许将
&mycurve1
传递给bar(const curve *)
。 Also with const float [...
allows passing mycurve1.xs
to foo(const float *)
.还使用
const float [...
允许将mycurve1.xs
传递给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
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.