且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

分配到阵列中的C结构

更新时间:2023-02-05 14:28:51

语法东西= {初始值} 只允许在初始化其中一个对象被定义,如:

The syntax something = { initial values } is allowed only in initializations, where an object is defined, such as:

long mem[1000] = { 1, 2, 3, 4, 5, 6 };

这是前pression如 X =值分配并不能使用语法初始化。

An expression such as x = value is an assignment and cannot use the syntax for initializations.

一个替代方案是创建一个临时对象,初始化,然后将该临时对象的内容复制到目标:

One alternative is to create a temporary object, which you initialize, and then copy the contents of that temporary object into the target:

static const long temporary[] = { 1, 2, 3, 4, 5, 6 };
memcpy(test->mem, temporary, sizeof temporary);

关于修改

阵列不得转让; X =值不是有效的,如果 X 是一个数组。然而,结构可以被分配,因此,另一种选择是创建一种结构作为一个临时对象,进行初始化,并分配它

Arrays may not be assigned; x = value is not valid if x is an array. However, structures may be assigned, so another alternative is to create a structure as a temporary object, initialize it, and assign it:

// (After the malloc is successful.)
static const Test temporary = { { 1, 2, 3, 4, 5, 6 } };
*test = temporary;

但是请注意,这code做了事先code不。现有的例子,我只是表现出副本六大要素入阵。这code创建类型为测试,其中包含1000个元素,一个临时的对象大多为零,它会将所有这些元素的进 *测试。即使编译器优化了这一点,并使用了一些code清除 *测试,而不是实际拷贝存储在内存中的零,它需要的不仅仅是复制六个元素更长的时间。所以,如果你只是想一些元素初始化并不在乎休息,使用前者code。如果你想初始化所有元素(大多数为零),则可以使用后者code。 (即使是这样,我会考虑替代方案,如使用释放calloc 而不是的malloc

Note, however, that this code does something the prior code does not. The prior example I showed merely copies six elements into the array. This code creates a temporary object of type Test, which contains 1000 elements, most of them zero, and it copies all of those elements into *test. Even if the compiler optimizes this and uses some code to clear *test rather than actually copying zeroes stored in memory, it takes longer than just copying six elements. So, if you just want a few elements initialized and do not care about the rest, use the former code. If you want all the elements initialized (most to zero), you can use the latter code. (Even so, I would consider alternatives, like using calloc instead of malloc.)