Assigning C / C ++ Arrays

Code example:

int ar[3];
............
ar[0] = 123;
ar[1] = 456;
ar[2] = 789;

Is there any way to cut it? Sort of:

int ar[3];
............
ar[] = { 123, 456, 789 };

I don't need a solution like:

int ar[] = { 123, 456, 789 };

Definition and initialization should be separate.

+3
source share
5 answers

What you ask for cannot be done directly. However, there are different things that you can do there, starting with creating a local array initialized using aggregate initialization, and then memcpyaccording to your array (valid only for POD types) or using higher-level libraries such as boost::assign.

// option1
int array[10];
//... code
{
   int tmp[10] = { 1, 2, 3, 4, 5 }
   memcpy( array, tmp, sizeof array ); // ! beware of both array sizes here!!
}  // end of local scope, tmp should go away and compiler can reclaim stack space

, boost::assign, .

+5

:

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

++.

0

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

this does not work for you?

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

    printf("%d %d %d\n", a[0], a[1], a[2]);
    printf("Size: %d\n", (sizeof(a) / sizeof(int)));

}

prints:

1 3 2
Size: 3
0
source
#include <iostream>

using namespace std;

int main()
{
    int arr[3];
    arr[0] = 123, arr[1] = 345, arr[2] = 567;
    printf("%d,%d,%d", arr[0], arr[1], arr[2]);
    return 0;
}
0
source

How about initializing a C99 array?

int array[] = {
   [0] = 5, // array[0] = 5
   [3] = 8, // array[3] = 8
   [255] = 9, // array[255] = 9
};
0
source

Source: https://habr.com/ru/post/1782078/


All Articles