《C99标准》增加了各种有益的办法,以启动结构,但并未提供重复经营人(Fortran自此就一直有过——但可能的话说是why。
If you are using a sufficiently recent version of GCC and you can afford to use a non-portable extension, then GCC provides an extension. In the GCC 8.1.0 manual (§6.27 Designated Initializers), it says:
To initialize a range of elements to the same value, write ‘[first ... last] = value’.
This is a GNU extension. For example,
int widths[] = { [0 ... 9] = 1, [10 ... 99] = 2, [100] = 3 };
如果其价值具有副作用,则只会产生副作用,而不是由范围初始的每个领域。
So, using this in your example:
struct memPermissions memPermissions[numBoxes] =
{
[0..numBoxes-1] = {-1, -1}, // GCC extension
};
我希望这在《标准》中;这非常有益!
Without using that or other similar compiler-specific mechanisms, your only choice is a loop. For a complex initializer with many fields, not all the same value, you can probably use:
#include <string.h>
#include "memperm.h" // Header declaring your types and variables
static int initialized = 0;
// -2 so the initialization isn t uniform and memset() is not an option
static const struct memPermissions initPermissions = { -1, -2 };
struct memPermissions memPermissions[numBoxes];
void initialize_permissions(void)
{
if (initialized == 0)
{
for (int i = 0; i < numBoxes; i++)
memmove(&memPermissions[i], &initPermissions, sizeof(initPermissions));
initialized = 1;
}
}
您也可在此使用<代码>memcpy()—不存在两种变数重叠的危险。
Now you just need to ensure that initialize_permissions()
is called before the array is used - preferably just once. There may be compiler-specific mechanisms to allow that, too.
您可以使用<代码>中的一种当地变量,即“优化”功能,取代最初确定的固定变量,即确保您的汇编者在要求履行这一职能时都先入选。
If you have a C99 compiler, you can use a compound literal in place of the constant:
void initialize_permissions(void)
{
if (initialized == 0)
{
for (int i = 0; i < numBoxes; i++)
memmove(&memPermissions[i],&(struct memPermissions){ -1, -2 },
sizeof(memPermissions[0]));
initialized = 1;
}
}