Declaring and initializing arrays in C

前端 未结 8 2129
北海茫月
北海茫月 2020-12-01 03:15

Is there a way to declare first and then initialize an array in C?

So far I have been initializing an array like this:

int myArray[SIZE] = {1,2,3,4..         


        
8条回答
  •  青春惊慌失措
    2020-12-01 04:02

    No, you can't set them to arbitrary values in one statement (unless done as part of the declaration).

    You can either do it with code, something like:

    myArray[0] = 1;
    myArray[1] = 2;
    myArray[2] = 27;
    :
    myArray[99] = -7;
    

    or (if there's a formula):

    for (int i = 0; i < 100; i++) myArray[i] = i + 1;
    

    The other possibility is to keep around some templates that are set at declaration time and use them to initialise your array, something like:

    static const int onceArr[]  = {  0,  1,  2,  3,  4,..., 99};
    static const int twiceArr[] = {  0,  2,  4,  6,  8,...,198};
    :
    int myArray[7];
    :
    memcpy (myArray, twiceArr, sizeof (myArray));
    

    This has the advantage of (most likely) being faster and allows you to create smaller arrays than the templates. I've used this method in situations where I have to re-initialise an array fast but to a specific state (if the state were all zeros, I would just use memset).


    You can even localise it to an initialisation function:

    void initMyArray (int *arr, size_t sz) {
        static const int template[] = {2, 3, 5, 7, 11, 13, 17, 19, 21, ..., 9973};
        memcpy (arr, template, sz);
    }
    :
    int myArray[100];
    initMyArray (myArray, sizeof(myArray));
    

    The static array will (almost certainly) be created at compile time so there will be no run-time cost for that, and the memcpy should be blindingly fast, likely faster than 1,229 assignment statements but very definitely less typing on your part :-).

提交回复
热议问题