Advertisement
Advertisement


Zero an array in C code


Question

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.

2017/05/23
1
43
5/23/2017 10:31:23 AM

Accepted Answer

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.


2011/04/12
88
4/12/2011 1:45:00 PM


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.

2011/04/12

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').
2011/04/12

Using memset:

int something[20];
memset(something, 0, 20 * sizeof(int));
2011/04/12

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

2011/04/12

Source: https://stackoverflow.com/questions/5636070
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]