Setting an array to one value

后端 未结 5 838
孤城傲影
孤城傲影 2020-12-09 17:14

Is there an easier way in C to set an array to one value than using a for loop and going setting each value one by one?

5条回答
  •  遥遥无期
    2020-12-09 17:43

    If it's an array of byte values, or you want to set each byte to a specific value, you can use memset:

    char xyzzy[100];
    int plugh[40];
    memset (xyzzy, 7, sizeof (xyzzy)); // all chars set to 7.
    memset (plugh, 0x42, sizeof (plugh));  // all integers set to (e.g.) 0x42424242.
    

    Another possibility is to create a template of the correct size at initialisation time (either real initialisation as per below, or in an init function), then call memcpy to blat (a) it onto the real array at a later date.

    static int template[] = { 1, 1, 1, 1, 1 };
    int zorkmid[3];
    memcpy (zorkmid, template, sizeof (zorkmid)); // ensure template is at
                                                  // least as big as zorkmid.
    

    This latter method is also handy for populating structures with a fixed pre-calculated value: initialise a dummy copy with the required fields set then memcpy it instead of manually setting all the fields each time you want a new instance.


    (a) Aside: etymology of blat:

    The Jargon file (see the glossary for all the definitions) lists blat as either the four metasyntactic variable {foo, bar, thud, blat}, or a synonym for blast, sense 1.

    In turn, blast (sense 1) is defined as a synonym of BLT (that's not the sandwich), which "referred to any large bit-field copy or move operation".

提交回复
热议问题