C/C++ arrays assignment

≯℡__Kan透↙ 提交于 2019-12-10 19:14:29

问题


Sample code:

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

Is there any way to init it shorter? Something like:

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

I don't need solution like:

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

Definition and initialization must be separate.


回答1:


What you are asking for cannot be done directly. There are, however different things that you can do there, starting from creation of a local array initialized with the aggregate initialization and then memcpy-ed over your array (valid only for POD types), or using higher level libraries like 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

I don't have time to check how to do this with boost::assign, as I hardly ever work with raw arrays.




回答2:


Arrays can be assigned directly:

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

Check the C++ Arrays tutorial, too.




回答3:


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

this doesn't 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



回答4:


What about the C99 array initialization?

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



回答5:


#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;
}


来源:https://stackoverflow.com/questions/4530319/c-c-arrays-assignment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!