如何在 C 中重置数组

How to reset array in C

cards[] = {2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11};

我有这个数组用于我的游戏,当我在我的数组中使用了一个数字时,它将被替换为 0。游戏结束后我需要重置数组,否则 0 将留在数组中。

如何重置该数组?

有两个数组:一个具有默认设置,一个可以修改。当"resetting"从默认数组复制到你修改的数组时

你可以使用一个函数,比如 Initialize,它使用 memcopy(或手动编码的循环)用一些预定义的值填充数组;无法将一些初始状态恢复到数组。

你不能。您需要制作一个不会更改的数组并将其复制到工作数组。根据需要重复复制。

为初始值定义一个数组,为工作值定义另一个数组:

const int init_cards[] = {2,2,2,2,3,3...};
int cards[sizeof init_cards / sizeof init_cards[0]];

...
memcpy( cards, init_cards, sizeof cards );  // reset values

要重置 - 将 init_cards 复制到 cards

创建一个存储原始值的数组。当你想重置它时,把它复制到原来的字符串:

int temp_cards[] = {2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11};
int cards[] = {2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11};
...
memcpy( cards, init_cards, sizeof cards );    // copying temp_card to card and resetting card
建议使用

memcpy,但如果您想保持简单,也可以使用 = 将一个字符串复制到另一个字符串。


@Dandorid 推荐的另一种方法很好,只是我会告诉你如何做:

void reset (int *cards) {
    int temp_cards[] = {2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11};
    memcpy (cards, temp_cards, sizeof (cards));
}

调用它时,传递 cards 数组。

创建一个初始化数组的函数;然后在每场比赛开始时调用它。