Fastest way to zero out a 2d array in C?

前端 未结 12 1274
后悔当初
后悔当初 2021-01-29 18:58

I want to repeatedly zero a large 2d array in C. This is what I do at the moment:

// Array of size n * m, where n may not equal m
for(j = 0; j < n; j++)
{
            


        
12条回答
  •  再見小時候
    2021-01-29 19:08

    This happens because sizeof(array) gives you the allocation size of the object pointed to by array. (array is just a pointer to the first row of your multidimensional array). However, you allocated j arrays of size i. Consequently, you need to multiply the size of one row, which is returned by sizeof(array) with the number of rows you allocated, e.g.:

    bzero(array, sizeof(array) * j);
    

    Also note that sizeof(array) will only work for statically allocated arrays. For a dynamically allocated array you would write

    size_t arrayByteSize = sizeof(int) * i * j; 
    int *array = malloc(array2dByteSite);
    bzero(array, arrayByteSize);
    

提交回复
热议问题