Initialize 2D Array C++ To Zero

In this article, we will discuss different ways we can initialize 2D array to Zero in C++.

Different Methods to Initialize 2D Array To Zero in C++

Method 1

int array[100][50] = {0};

The above code initialize a 2D array with all entries 0.

The above code snippet actually sets the first element of the array to 0 and sets the rest of the array to 0. For example, if we replace the ‘0’ by some other digits say ‘1’. We won’t get an array with all 1. We will obtain an array with the first index, which is array[0][0] equal to 1, and the result of the elements equal to 0.

#include<iostream>
using namespace std;

void Print2DArray(int arr[][20], int r, int c){
	for(int i=0;i<r;++i){
		for(int j=0;j<c;++j){
			cout<<arr[i][j]<<' ';
		}	
		cout<<endl;
	}
	cout<<endl;
}

int main() {
	
	int arr[20][20] = {0};
	int r,c;
	r = 4;
	c = 3;
	cout<<"2D Array"<<endl;
	Print2DArray(arr,r,c);
	
}

Output

Initialize 2D Array C++ To Zero

Method 2

Now, the previous method works perfectly but there might be a situation where we may modify the array but later wants to set all entries of the array to zero. To solve this problem, we may use std::memset.

Syntax

int arr[100][100]
memset( arr, 0, sizeof(arr) )

The above code will set all entries of arr to zero.

std::memset is a standard library function. It is defined in <cstring> header file. It accepts 3 parameters.

  1. First is the starting address of the array.
  2. Second is the value we want to assign to each entry of the array.
  3. The last one is the size of the array.
#include<iostream>
#include<cstring>
using namespace std;

void Print2DArray(int arr[][20], int r, int c){
	for(int i=0;i<r;++i){
		for(int j=0;j<c;++j){
			cout<<arr[i][j]<<' ';
		}	
		cout<<endl;
	}
	cout<<endl;
}

int main() {
	
	int arr[20][20];
	int r,c;
	r = 4;
	c = 3;
	
	for(int i=0;i<r;++i){
		for(int j=0;j<c;++j){
			arr[i][j] = i*c+j;
		}	
	}
	
	cout<<"Array Before memset"<<endl;
	Print2DArray(arr,r,c);
	
	memset(arr, 0, sizeof(arr));
	
	cout<<"Array After memset"<<endl;
	Print2DArray(arr,r,c);
	
}

Output

set all entries of 2D array to zero using memset

Method 3

We can also initialize an array with all zeroes by declaring it globally. Every global variable is initialized with all zeros.

#include<iostream>
#include<vector>
using namespace std;

int arr[20][20];

void Print2DArray(int arr[][20], int r, int c){
	for(int i=0;i<r;++i){
		for(int j=0;j<c;++j){
			cout<<arr[i][j]<<' ';
		}	
		cout<<endl;
	}
	cout<<endl;
}



int main() {

	int r,c;
	r = 4;
	c = 3;
	cout<<"2D Array"<<endl;
	Print2DArray(arr,r,c);
	
}

Output

declare 2D array with all zeros

Method 4

This is brute force method. Use 2 nested loops and set each element of the array to 0.

References

std::memset

Leave a Comment

Your email address will not be published.