Assigning an entire array with a single statement

后端 未结 5 1898
闹比i
闹比i 2021-01-11 20:53

Let us say that I declare and initialize

int a[3] = {1, 2, 3};

How can I later asisgn the entire array in one fell swoop? i.e.



        
相关标签:
5条回答
  • 2021-01-11 21:07

    Here's a non-portable way of doing it that, strictly speaking, can also involve undefined behavior:

    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
      int a[3] = { 1, 2, 3 };
      printf("%d,%d,%d\n", a[0], a[1], a[2]);
      // assuming ints are 4-bytes-long, bytes are 8-bit-long and
      // the byte order in ints is from LSB to MSB (little-endian):
      memcpy(a, "\x03\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00", sizeof(a));
      printf("%d,%d,%d\n", a[0], a[1], a[2]);
      return 0;
    }
    

    Output:

    1,2,3
    3,2,1
    
    0 讨论(0)
  • 2021-01-11 21:22

    You can't; you'll need to use something like memset if the values are all the same (and each element is a byte big), or a simple for-loop if they're not a byte big and if the numbers can be calculated. If the values cannot be calculated at runtime, you'll need to do each one by hand like a[x] = y;.

    The reason they are called "initialiser lists" is because they can be used to initialise something, and initialisation by definition only happens once.

    0 讨论(0)
  • 2021-01-11 21:28

    compound literal is part of ANSI C (C99). Since it is part of the language, any compiler claiming to be conforming to C99 must support this:

    memcpy(a, (int[]){3, 2, 1}, sizeof a);

    gcc can be invoked as "gcc -Wall -W -std=c99 -pedantic" to specify the standard.

    Since it is more than 11 years since C99, I think it's safe and probably a good idea to start using the new capabilities the language provides.

    compound literals are discussed in section 6.5.2.5 of n869.txt

    0 讨论(0)
  • 2021-01-11 21:29

    If your c compiler supports compound literals, you can use memcpy:

    memcpy(a, (int[]){3, 2, 1}, sizeof a);
    

    If you don't plan to stick any variables in there (you can; isn't C99 amazing?), (int[]) can be replaced by (const int[]) to put the literal into static memory.

    0 讨论(0)
  • 2021-01-11 21:30

    You cannot do that. An array can only be initialized from a brace expression in a declarator-initializer. You assign arrays.

    In C89 there wasn't even such a thing as a "temporary array", though as of C99 these exist by virtue of compound literals (see @Dave's answer).

    0 讨论(0)
提交回复
热议问题