Zero-initializing an array data member in a constructor

后端 未结 5 1223
予麋鹿
予麋鹿 2020-12-17 16:16

I\'ve got an array of class objects, and inside the class object I\'ve got another array that I\'d need to initialize to all zeros. The code compiles and runs, but my outpu

5条回答
  •  佛祖请我去吃肉
    2020-12-17 16:51

    There are two problems with your code:

    byte[16]={0};
    

    Array has 0 based index, so maximum index in this case can be 15, not 16. You are corrupting the memory.

    Second, you have to loop through all the elements and initialize them. The way you are initializing will be done for one element only.

    Cache::Cache()  
    {
      for(int i=0;i<16;i++)
       byte[i]=0;
    }
    

提交回复
热议问题