English 中文(简体)
C中一系列构件的定本
原标题:Static initialization of an array of structs in C

我对C.Googling的一系列建筑的初始化有疑问,这给我表明,很多人有着非常相似的问题,但问题并不相同。

Essentially, I have a global array of structs of type "memPermissions" shown below. This array needs all the "address" and "ownerId" fields to be initialized to -1 upon program execution.

typedef struct memPermissions {
    int address;
    int ownerId;
} *test;

问题是,阵列的大小是用一只标准,因此我只能说:

#define numBoxes 5

struct memPermissions memPermissions[numBoxes] = {
{-1, -1},
...
{-1, -1}
};

我尝试:

struct memPermissions memPermissions[numBoxes] = {-1, -1};

但自然,这只是第一点。 (其余部分定为0)。 引起人们注意的唯一解决办法是,在某个地方以简单的形式开始使用,但由于该法典的运行性质,我真心希望,这不是我的唯一选择。

如果没有 lo,是否有什么办法可以初步确定这些 array体的所有要素?

Cheers, -Josh

最佳回答

引起人们注意的唯一解决办法是,在某个地方以简单的形式启动。

我担心,这是语言中的唯一可能性。 在C,你要么明确开始每个要素,要么开始全部零,要么没有开始。

However, you can sidestep the issue by using 0 for the purpose that your -1 currently serves.

问题回答

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

你可以撰写一份外部方案,通过你想要的物品数量。 这一方案应当由您的马克文或等同文提出。 该方案将撰写一份载有1-1级价值所需数目的文件以及<代码>#define。

如您有标准图书馆,可使用<代码>memset,加上<代码>sizeof (struct memPermissions) * numBoxes,以填补您的阵列上任何统一的附则值。 由于-1号是0xFFFFFFFF>,因此,这可能对你有用。

If it really important to not use a loop, you could do something rather strange, and use/abuse memset assuming that is available.

N.B. 哺乳期可使用假体实施,因此可能没有实际意义。

memset(memPermissions, 0xFF, sizeof(memPermissions)*numBoxes*2*sizeof(int));

The times 2 is needed for both members of the struct (i.e. two of them).

之所以设计不好,是因为这取决于结构不是附加的,也不是协调的,汇编者可根据C规格自由这样做。

(Utilizing that -1 is typically 0xFFFFFFFF for 2-compliment negative integers on 32-bit processors, with 32-bit int. Kudos to @James for pointing this out.)

Though I would suspect in most cases that the code would be implemented as a small, fast, tight loop (rep movsd for x86) in assembly language in all but the most trivial of cases (very small values of numBoxes).





相关问题
Fastest method for running a binary search on a file in C?

For example, let s say I want to find a particular word or number in a file. The contents are in sorted order (obviously). Since I want to run a binary search on the file, it seems like a real waste ...

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

Tips for debugging a made-for-linux application on windows?

I m trying to find the source of a bug I have found in an open-source application. I have managed to get a build up and running on my Windows machine, but I m having trouble finding the spot in the ...

Trying to split by two delimiters and it doesn t work - C

I wrote below code to readin line by line from stdin ex. city=Boston;city=New York;city=Chicago and then split each line by ; delimiter and print each record. Then in yet another loop I try to ...

Good, free, easy-to-use C graphics libraries? [closed]

I was wondering if there were any good free graphics libraries for C that are easy to use? It s for plotting 2d and 3d graphs and then saving to a file. It s on a Linux system and there s no gnuplot ...

Encoding, decoding an integer to a char array

Please note that this is not homework and i did search before starting this new thread. I got Store an int in a char array? I was looking for an answer but didn t get any satisfactory answer in the ...

热门标签