[英]Initializing struct containing arrays
我在 C 中有一个结构,其中成员是浮点数组。 我想在编译时像这样初始化它:
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
};
但我收到编译错误。
一种可能的解决方案可能是在结构中使用数组而不是指针。 这是这里一个非常相似的问题的公认答案: https : //stackoverflow.com/a/17250527/1291302 ,但这种方法的问题是我不知道 typedef 时的数组大小。 不仅如此,我可能还想初始化另一个更大的曲线。
另一种方法可能是使用 malloc,但我发现这有点矫枉过正,因为我在编译时知道数组大小,而且我不需要在运行时更改它。
我不知道其他可能有用的方法。 也许将数组转换为指针? - 我真的不知道我会如何处理。
您不能像使用包含多个初始值设定项的花括号列表的指针一样初始化标量对象。
但是您可以使用复合文字。
这是一个演示程序。
#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;
}
它的输出是
1.0 2.0 3.0
0.0 0.3 0.9 1.5
const
时使用const
因为我在编译时知道数组大小,并且我不需要在运行时更改它。
考虑const curve mycurve1 = ...
。 这允许选择优化,识别误用并允许将&mycurve1
传递给bar(const curve *)
。 还使用const float [...
允许将mycurve1.xs
传递给foo(const float *)
。
避免幻数
#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.