零出在C二维数组最快的方法? [英] Fastest way to zero out a 2d array in C?

查看:183
本文介绍了零出在C二维数组最快的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想重复在零C.这是一个大的二维数组是我目前做的:

 为(J = 0; J< N; J ++)
{
    对于(i = 0; I< N;我++)
    {
        数组[I] [J] = 0;
    }
}

我用memset尝试:

  memset的(数组,0,sizeof的(阵列))

但是,这仅适用于一维数组。当我printf的二维数组的内容,第一行是零,但后来我得到了随机大量的负载,它崩溃。


解决方案

  memset的(数组,0,sizeof的(阵列[0] [0])* M * N);

其中, M N 是二维数组的宽度和高度(在你的榜样,你有一个方形二维数组,所以米==ñ)。

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

for(j = 0; j < n; j++)
{
    for(i = 0; i < n; i++)
    {  
        array[i][j] = 0;
    }
}

I've tried using memset:

memset(array, 0, sizeof(array))

But this only works for 1D arrays. When I printf the contents of the 2D array, the first row is zeroes, but then I got a load of random large numbers and it crashes.

解决方案

memset(array, 0, sizeof(array[0][0]) * m * n);

Where m and n are the width and height of the two-dimensional array (in your example, you have a square two-dimensional array, so m == n).

这篇关于零出在C二维数组最快的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆