×

How to initialize array to zero in C

In this article, you will learn how to initialise an array to 0 in C

In C, an array is declared as:

char ZEROARRAY[2022];

The global scope changes at runtime to all zeros. If the array is local, there is a shortcut method. As shown below, the declaration and initialization.

char ZEROARRAY[1024] = {0};

When an array is partially initialised, the value 0 of the appropriate data type will be applied to any items that are not initialised. The compiler will insert zeros into any unwritten entries.

The static storage-equipped objects initialise to 0 if no initializer is given. The declaration reads as follows:

static int myArray[20];

An array is initialized to 0 if the initializer list is empty or 0 is specified in the initializer list. The declaration is as given below:

int number[10] =  { };
int number[10] =  { 0 };

However, the array is given all useless values by merely making this declaration. There are a variety of circumstances and cases in which we must initialise each element to ZERO (0) before doing any additional calculations.

The most simplistic initialization method is to cycle through all the components and set them all to 0.

int arr[100];
int k = 0;
for(k = 0 ; k < 50 ; k++)
    arr[k] = 0;  // All will then be zero as a result.

We also have the following 3 basic methods.

1) Static and global variables are both initialised automatically to zero. At runtime, an array that is in the global scope will be empty.

int arr[2022]; // Global in scope
int main(void)
{
    // the statements
}

2) If you had a local array, there is also a shorthand syntax available. If an array is partially initialised, the value 0 of the proper type is assigned to any uninitialized items. The unwritten entries would be filled with zeros by the compiler. You might type:

int main(void)
{
    int arr[2022] = {0};  // All will thereafter become ZERO.
    // the statements
}

As an alternative, you may populate the array using memset when the programme launches. If you altered it and wished to reset it to zeros, this command is quite helpful.

int arr[2022];
arr[10] = 60;
memset(zeroarray, 0, 2022); // This will reset everything to zero.

We can include the two contents here:

  • Use memset() from the C library
  • Set the Array's initial values to something other than 0.

Looping through every element and setting them all to 0 is the simplest way to initialise an array.

#include <stdio.h>
#include<conio.h>
int main(void)
{
    int numberArray[20], kamar;
    for(kamar = 0 ; kamar < 10 ; kamar++)
    {
        numberArray[kamar] = 0;
    }
    printf("Elements of the Array are:\n");
    for(kamar=0; kamar<10; kamar++)
    {
        printf("%d",numberArray[kamar]);
    }
    return 0;
}

Output

How to initialize array to zero in C

Use memset() from the C library

The string.h library contains the function memset(). It is used to store a specific value in a block of memory.

The memset() function's syntax is as follows:

void *memset(void *pointerVariable, int anyValue, size_t numberOfBytes);

where,

  • a pointer Variable is a variable that points to the memory block that needs to be filled. Simply it can be called ptr for easy understanding.
  • The value that must be set is any Value. This number is an integer, but the function converts it to an unsigned char to fill the block of memory.
  • The amount of bytes that will be used to store the value is given by the number Of Bytes.

An access point to the memory location pointerVariable is returned by this function.

Let us see an example program for the above-mentioned category.

// C programme to illustrate the memset functionality ()
#include <stdio.h>
#include <conio.h>
#include <string.h>
void printArrayvalues(int anyArray[], int anyNumber)
{
    int literature;
    for (literature=0; literature<anyNumber; literature++)
        printf("%d ", anyArray[literature]);
}
int main(void)
{
    int num = 12;
    int arrayValues[num];
    // / Add zeros to the entire array.  
    memset(arrayValues, 0, num*sizeof(arrayValues[0]));
    printf("Array after the memset() is \n");
    printArrayvalues(arrayValues, num);
    return 0;
}

Output:

How to initialize array to zero in C

We also have that facility in which initialling the array to values other than 0 :

With gcc, initialising an array to something other than 0 looks like this:

int theArrayValues[2022] = { [ 0 ... 2021 ] = -1 };

By leaving off the dimension, an array can have every element directly populated. Here is the declaration:

Int theArrayValues[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1 };

Only the outermost dimension may be skipped for multidimensional arrays because the compiler will infer the dimension from the initializer list.

int thePoint[][3] = { { 9, 8, 7 }, { 6, 5, 4 }, { 3, 2, 1} };

Related Topics

Decimal to Binary in C

What is a decimal number? A decimal number is a number represented in the decimal number system. This system of binary conversion uses base 10 to represent numbers, i.e. the digits...

3 minutes read.

Types Of Structures In C

We can normally store elements of the same datatype with the help of an array in C programming. We can store multiple numbers of elements of a character data type...

3 minutes read.

Kruskal algorithm in C

Given a weighted graph, Kruskal's algorithm generates a spanning tree with the lowest possible weights. Start by creating an edge list for the given graph, including the weights. Sort the...

3 minutes read.

Exit control loop in C

To examine the termination condition for an exit, we usually use an exit control loop in C. If the evaluation for termination condition results in true, then the control would...

3 minutes read.

Flow Chart of For loop in C

This is a flowchart that represents the process of executing the for loop in the C programming language. Generally, as we know there are three main components of for loop:1. The...

3 minutes read.

Pointer arithmetic in C

In the C programming language, a pointer is an address which stores a numeric value. Hence, a developer can perform several arithmetic operations on the same just as one does...

4 minutes read.

Sum of N numbers in C using For loop

Before we move on the program of sum of N numbers, first we have to know about the For Loop statement. The syntax of ‘for’ loop in C programming language is...

3 minutes read.

C Program of Fencing the Ground

The college's ground is rectangular. Fencing the ground the management makes the decision to construct a fence around the ground. They planned to wrap a thick rope around the ground...

1 minute read.

Sum of digits in C++

Sum of digits in C++ There are various ways to find the sum of the digits of a number in C++. We can use containers like arrays or other simple cases...

4 minutes read.

String literals in C

Constants refer to the fixed values of the program that may not alter during the compiling ad execution. These fixed values are known as literals. In other words, the values...

3 minutes read.

What is 2s Complement in C?

The complement of 2s in C is generated from the 1s in C. As we know, the 1s complement of a binary number is generated by converting bit 1 to...

4 minutes read.

Array Of Structures in C

The C programming language allows us to store multiple elements of the same type in arrays. We can use strings to store multiple elements of a character data type. Still,...

4 minutes read.

Git Hooks

Git Hooks Overview Just like other version control systems, Git has its way to deliver customized scripts whenever some important activity occurs. The hooks act just like the triggers or catalysts...

4 minutes read.

Scope of variables in C

Introduction The scope of variables in C can be defined as the scope of reach of a variable, the term scope is used to determine the visible range of an object....

4 minutes read.

Enumeration (Enum) in C

Enumeration (Enum) in C: In the C programming language, the enum is referred to as an enumerated type. Enum is a user defined data type consisting of integer values and...

3 minutes read.

Attributes in C

Attributes are one of modern C++ key features. It is the process by which initiator can add more information to the language instead of introducing new keywords for every attribute....

4 minutes read.

Pointer in C

Pointer is a variable that is used to contain the address of another variable. We can easily create a pointer in C language. Example: int *ptr Symbol Description & (ampersand sign) Address of an operator...

1 minute read.

Fseek Function in C

The fseek function is a function in the C standard library that changes the position of the file pointer in a stream-oriented file. It is typically used to move the...

3 minutes read.

For Loop in C Programming Examples

The Syntax of the For Loop for (initialization statement; termination condition; modifying (increment/ decrement) statement) {       /* main body of the For loop */     } In for loop, the initialization command...

6 minutes read.

Socket Programming in C

Socket programming is a process that connects the two or more nodes on a networking communication with respective to each other. One of the sockets that determines the socket (I.e.,...

5 minutes read.