31

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

    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
    };
4

3 回答 3

35

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

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

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

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

于 2012-01-16T21:18:14.240 回答
12

如果您将数组包装在一个结构中,它就会变得可分配。

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.
于 2012-01-16T21:26:52.603 回答
0

数组和结构的这种表示法仅在初始化中有效,所以不。

于 2012-01-16T21:27:46.203 回答