简体   繁体   中英

What is the simplest way to reset array values to 0?

Assume we have a pointer(eg, defined as int* p) to the beginning of an array and the size of the array(eg, 1000). We want to reset all 1000 array values to 0. What is the simplest way?

最简单的方法是使用memset。

memset(p, 0, 1000 * sizeof(int));

Using memset() to zero the memory is good for your example of an array of int , or for any other integer type.

If the array is dynamically allocated, another option is to allocate it using calloc() instead of malloc() to guarantee that it is initially set to all bits zero.

For arrays of float or double (or pointers, if you want them initialised to NULL), using a loop is better, as these methods are not portable: there are no guarantees about the representations of these types, so all-bits-zero does not necessarily represent a floating point zero (although it happens to work for the most common format, IEEE 754) or a NULL pointer (although platforms where this is not the case are rare).

(See C99 §6.2.6 for the guarantees about integer types; and the footnote for calloc() in §7.20.3.1.)

I'd go with:

#include <string.h>

memset(p, 0, 1000 * sizeof(p[0]));

If you want speed, use the standard library function memset. It essentially just loops through each value and writes a zero, but it's been optimized for speed.

void * memset ( void * ptr, int value, size_t num );

The prototype is included in string.h .

您可以使用bzero,memset或普通循环。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM