开发者

Zero an array in C code [duplicate]

开发者 https://www.devze.com 2023-02-25 12:51 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicates: How to initialize an array to something in C without a loop?
This question already has answers here: Closed 11 years ago.

Possible Duplicates:

How to initialize an array to something in C without a loop?

How to initialize an array in C

How can I zero a known size of an array without using a for or any other开发者_StackOverflow中文版 loop ?

For example:

arr[20] = 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0;

This is the long way... I need it the short way.


int arr[20] = {0};

C99 [$6.7.8/21]

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.



int arr[20];
memset(arr, 0, sizeof arr);

See the reference for memset


Note: You can use memset with any character.

Example:

int arr[20];
memset(arr, 'A', sizeof(arr));

Also could be partially filled

int arr[20];
memset(&arr[5], 0, 10);

But be carefull. It is not limited for the array size, you could easily cause severe damage to your program doing something like this:

int arr[20];
memset(arr, 0, 200);

It is going to work (under windows) and zero memory after your array. It might cause damage to other variables values.


int arr[20] = {0} would be easiest if it only needs to be done once.


man bzero

NAME
   bzero - write zero-valued bytes

SYNOPSIS
   #include <strings.h>

   void bzero(void *s, size_t n);

DESCRIPTION
   The  bzero()  function sets the first n bytes of the byte area starting
   at s to zero (bytes containing '\0').


Using memset:

int something[20];
memset(something, 0, 20 * sizeof(int));
0

精彩评论

暂无评论...
验证码 换一张
取 消