Why is it worse to initialize a two dimensional array like this?

前端 未结 4 1754
有刺的猬
有刺的猬 2020-12-10 13:40
for(int i = 0; i<100; i++)

    for(int j = 0; j<100; j++)

         array[j][i] = 0;
         // array[i][j] = 0;

My professor said it was m

4条回答
  •  时光取名叫无心
    2020-12-10 14:04

    I'll probably get downvoted for this, but if you are programming C, then the "best" is most likely:

    memset(array, 0, sizeof(array));

    Then you can defer all responsibility of optimizing (which you are obviously worried about) to the implementation of memset. Any specific hardware advantages can be done there.

    http://en.wikipedia.org/wiki/Sizeof#Using_sizeof_with_arrays/

    http://www.cplusplus.com/reference/clibrary/cstring/memset/

    Another observation is that if you are init'ing to zero, ask yourself why? If your array is static (which for this large it probably is?), then cstartup will initialize to zero for you. Again, this will probably use the most efficient way for your hardware.

提交回复
热议问题