同时修改数组的所有元素

时间:2016-10-14 15:52:57

标签: c arrays

有没有办法同时修改数组的所有元素? 我的意思是for循环只是循环遍历数组并逐个完成所有事情。

注意: 这是.gsc / .csc(这是一种自己的编程语言),但它遵循基本的C语法:

function setCOD7DecodeFx()
{
    alphabet = strTok("a b c d e f g h i j k l m n o p q r s t u v w x y z", " ");
    test = "text";
    is_done = false;

    //I want all of the letters of text to change at the same time
    while(!is_done)
    {
        //I want this to happen without having to do text[num]
        test[0] = alphabet[rand(0, alphabet.size - 1)];
        test[1] = alphabet[rand(0, alphabet.size - 1)]; //rand -> rand(min, max)
        test[2] = alphabet[rand(0, alphabet.size - 1)]; //alphabet.size -> counts all elements in an array
        test[3] = alphabet[rand(0, alphabet.size - 1)];
        wait 0.25;
    }
    wait 3;
    is_done = true;
    test = "text";
}

它是否适用于foreach声明?我知道'foreach'在C中不存在,但它存在于gsc中。

foreach(element in array)

1 个答案:

答案 0 :(得分:0)

要修改数组,例如test(不超过int字符的大小),代码可以使用以下具有许多限制的内容(endian,int大小等。)。

#include<stdlib.h>

int main(void) {
    const unsigned base_letter = 'a';
    const unsigned offset_pow2 = 5;  // a-z and "{|}~" and code 127

    const unsigned char_mask = (1u << offset_pow2) - 1;
    unsigned mask = 
        char_mask << 24 | char_mask << 16 | char_mask << 8 | char_mask;
    unsigned offset = 
        base_letter << 24 | base_letter << 16 | base_letter << 8 | base_letter;
    union {
      char test[5];
      unsigned r;
    } u = { "text" };
    u.r = (rand() & mask) + offset;  // Set all characters at once
    printf("<%s>\n", u.test);
}

输出

<nury>