×

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

Booleans in C

Introduction to Boolean With all the complexities of programming, it can take time to understand the basics. One concept, in particular, that confuses many beginners is the use of Booleans in...

6 minutes read.

Explain the Increment and Decrement Operators in C

In the C programming language, the increment operator (++) and the decrement operator (--) are used to increase or decreasing a variable’s value by 1, respectively. The increment operator is written...

10 minutes read.

How to use atoi() function in C

Introduction: The atoi() is a function used in C programming language. This function converts string characters to the integer value. The atoi() function converts the input string to the return type of...

4 minutes read.

Add two numbers using the function in C

Here we will learn how to add two numbers by creating function in C. Let’s learn this with help of example. Code: - #include <stdio.h> int add_two_no(int a, int b); int main(){   int first_num,...

1 minute read.

Variable in C

Variable is an identifier that holds data in memory. It is used to identify input data in a program. The value of the variable can change at the time of...

2 minutes read.

Dynamic memory allocation

Dynamic memory allocation is used to allocate the memory at runtime. It has following function within <stdlib.h> header file. Function Syntax malloc() malloc (number *sizeof(int)); calloc() calloc (number, sizeof(int)); realloc() realloc (pointer_name, number * sizeof(int)); free() free (pointer_name); malloc() function The process...

2 minutes read.

7 Best IDEs for C/C++ Developers in 2024

As we all know that in programming languages, C is known as the building block which cannot be contradicted, and C++ is the prolong kind of C and it can...

4 minutes read.

Long int in C

We use data type to avoid the type of data to be stored for a variable at the time of declaration.So, we can say that the variable type is known...

3 minutes read.

How to move a text in C

A text can be moved to the desired location in the output based on the coordinates provided in the gotoxy() function. What is gotoxy() function? In C language, gotoxy() is a pre-defined...

3 minutes read.

Bigint (BIG INTEGERS) in C with Example

The maximum number of digits that a long, long int can have in C/C++ is 20. The issue is how to store the 22-digit number, which is difficult to do...

9 minutes read.

Data Structures And Algorithms in C

C language is one of the most flexible and simple languages. So, it is always better to learn any concept in C language compared to other languages. Let us look...

13 minutes read.

Character Set in C

Introduction Every language has some basic elements which are used to represent information. The English language includes alphabets which together shape a sentence, after which the sentences are used to shape...

3 minutes read.

C Data type

Data Types in C with Examples Data types are used to define the type of data that a variable can store to perform a specific operation.ANSI C provides three types of...

2 minutes read.

Program to Find Mode of an Array in C

Mode is the highest occurring value or number in a given set of data elements. In a group of data values, a value that occurs most frequently is considered to...

3 minutes read.

LCM of two numbers in C

LCM is a mathematical term which stands for Least Common Multiple. LCM of any two numbers is the smallest positive value(number) which is evenly divisible by the two given numbers. Consider...

4 minutes read.

Find median of 1D array using function in C

Introduction: Here, we discuss how we can find the median of a 1D array using a function in C. The median is the value in the middle of the sorted...

3 minutes read.

Multilevel Feedback Queue Scheduling (MLFQ) CPU Scheduling

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

3 minutes read.

Stdio.h in C

Header files are used to make the programmer’s efforts a lot easier. In order to make the programming simple, there are a number of libraries which are included as predefined...

4 minutes read.

Random function in C

Random function in C In the C programming language, the rand() is a function used for Pseudo Random Number Generator (PRNG). The random number generated by the rand() function is not...

4 minutes read.

Find out Power without using POW function in C

Introduction: In this discussion, we will discuss how we find out power without using the POW function in C. In this article, you'll understand how to compute integer powers in...

3 minutes read.