Initializing entire array with memset

前端 未结 4 1128
天涯浪人
天涯浪人 2021-01-19 13:09

I have initialised the entire array with value 1 but the output is showing some garbage value. But this program works correctly if i use 0 or -1 in place of 1. So are there

4条回答
  •  天涯浪人
    2021-01-19 13:43

    The other answers have explained std::memset already. But it's best to avoid such low level features and program at a higher level. So just use the Standard Library and its C++11 std::array

    #include 
    
    std::array a;
    a.fill(1);
    

    Or if you prefer C-style arrays, still use the Standard Library with the std::fill algorithm as indicated by @BoPersson

    #include 
    #include 
    
    int a[100];
    std::fill(std::begin(a), std::end(a), 1);
    

    In most implementations, both versions will call std::memset if it is safe to do so.

提交回复
热议问题