可以在C语句中声明后初始化数组吗?

时间:2012-01-16 21:17:02

标签: c variable-declaration

有没有办法在实际初始化它之前声明这样的变量?

    CGFloat components[8] = {
        0.0, 0.0, 0.0, 0.0,
        0.0, 0.0, 0.0, 0.15
    };

我希望它声明这样的东西(除了这不起作用):

    CGFloat components[8];
    components[8] = {
        0.0, 0.0, 0.0, 0.0,
        0.0, 0.0, 0.0, 0.15
    };

3 个答案:

答案 0 :(得分:30)

你不能分配到数组,所以基本上你不能做你的建议,但在C99你可以这样做:

CGFloat *components;
components = (CGFloat [8]) {
    0.0, 0.0, 0.0, 0.0,
    0.0, 0.0, 0.0, 0.15
};

( ){ }运算符称为复合文字运算符。这是一个C99功能。

请注意,在此示例中,components被声明为指针而不是数组。

答案 1 :(得分:8)

如果将数组包装在结构中,它将变为可赋值。

typedef struct
{
    CGFloat c[8];
} Components;


// declare and initialise in one go:
Components comps = {
    0.0, 0.0, 0.0, 0.0,
    0.0, 0.0, 0.0, 0.15
};


// declare and then assign:
Components comps;
comps = (Components){
    0.0, 0.0, 0.0, 0.0,
    0.0, 0.0, 0.0, 0.15
};


// To access elements:
comps.c[3] = 0.04;

如果使用此方法,还可以从方法返回Components结构,这意味着您可以创建函数来初始化并分配给结构,例如:

Components comps = SomeFunction(inputData);

DoSomethingWithComponents(comps);

comps = GetSomeOtherComps(moreInput);

// etc.

答案 2 :(得分:0)

数组和结构的表示法仅在初始化时有效,所以没有。

相关问题