乱世@小熊 2008-10-14 13:13 采纳率: 25%
浏览 500
已采纳

如何将数组的所有成员初始化为相同的值?

I have a large array in C (not C++ if that makes a difference). I want to initialize all members to the same value. I could swear I once knew a simple way to do this. I could use memset() in my case, but isn't there a way to do this that is built right into the C syntax?

转载于:https://stackoverflow.com/questions/201101/how-to-initialize-all-members-of-an-array-to-the-same-value

  • 写回答

19条回答 默认 最新

  • 谁还没个明天 2008-10-14 13:17
    关注

    Unless that value is 0 (in which case you can omit some part of the initializer and the corresponding elements will be initialized to 0), there's no easy way.

    Don't overlook the obvious solution, though:

    int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };
    

    Elements with missing values will be initialized to 0:

    int myArray[10] = { 1, 2 }; // initialize to 1,2,0,0,0...
    

    So this will initialize all elements to 0:

    int myArray[10] = { 0 }; // all elements 0
    

    In C++, an empty initialization list will also initialize every element to 0. This is not allowed with C:

    int myArray[10] = {}; // all elements 0 in C++
    

    Remember that objects with static storage duration will initialize to 0 if no initializer is specified:

    static int myArray[10]; // all elements 0
    

    And that "0" doesn't necessarily mean "all-bits-zero", so using the above is better and more portable than memset(). (Floating point values will be initialized to +0, pointers to null value, etc.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(18条)

报告相同问题?

悬赏问题

  • ¥15 聚类分析或者python进行数据分析
  • ¥15 如何用visual studio code实现html页面
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?