elliott.david 2008-10-14 13:13 采纳率: 25%
浏览 743
已采纳

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

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条回答

  • lrony* 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条)

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮