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

前端 未结 12 1246
后悔当初
后悔当初 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:25

    I think that the fastest way to do it by hand is following code. You can compare it's speed to memset function, but it shouldn't be slower.

    (change type of ptr and ptr1 pointers if your array type is different then int)

    
    #define SIZE_X 100
    #define SIZE_Y 100
    
    int *ptr, *ptr1;
    ptr = &array[0][0];
    ptr1 = ptr + SIZE_X*SIZE_Y*sizeof(array[0][0]);
    

    while(ptr < ptr1)
    {
        *ptr++ = 0;
    }
    

提交回复
热议问题