Zero an array in C code

CArrays

C Problem Overview


> 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 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.

C Solutions


Solution 1 - C

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.


Solution 2 - C

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

See the reference for memset

Solution 3 - C

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.

Solution 4 - C

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').

Solution 5 - C

Using memset:

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

Solution 6 - C

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBatmanView Question on Stackoverflow
Solution 1 - CPrasoon SauravView Answer on Stackoverflow
Solution 2 - COleh PrypinView Answer on Stackoverflow
Solution 3 - CRúben Lício ReisView Answer on Stackoverflow
Solution 4 - CdrysdamView Answer on Stackoverflow
Solution 5 - CiRaivisView Answer on Stackoverflow
Solution 6 - CChrisView Answer on Stackoverflow