C / C ++数组赋值 [英] C/C++ arrays assignment

查看:315
本文介绍了C / C ++数组赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

样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.

推荐答案

你问什么不能直接完成。有,但是不同的东西,你可以在那里做,从创建与集合初始化,然后的memcpy -ed在你的阵列(仅适用于POD初始化的本地数组的开始类型),或使用更高级别的库,例如的boost ::分配

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

我没有时间去检查如何与这样做的boost ::分配,因为我很少用生数组。

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

这篇关于C / C ++数组赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆