zero fill in c++
#include <iostream>
#include <cstring>
int main() {
const int size = 10;
int array[size];
std::memset(array, 0, sizeof(array));
// Printing the zero-filled array
std::cout << "Zero-filled array:" << std::endl;
for (int i = 0; i < size; ++i) {
std::cout << array[i] << " ";
}
std::cout << std::endl;
return 0;
}
This C++ program demonstrates zero-filling an array using the memset
function. Here's a step-by-step explanation:
#include <iostream>
: Includes the input/output stream for handling input and output operations.#include <cstring>
: Includes the C string handling library for functions likememset
.const int size = 10;
: Declares a constant variablesize
and initializes it to 10, representing the size of the array.int array[size];
: Declares an integer array namedarray
with a size defined by thesize
constant.std::memset(array, 0, sizeof(array));
: Uses thememset
function to set all elements in thearray
to zero. Thememset
function fills a block of memory with a particular value. Here, it sets0
for each element in the array. The parameters are:array
: Pointer to the starting address of the memory block to be filled.0
: The value (zero in this case) to be set.sizeof(array)
: Specifies the number of bytes to be filled, which is calculated as the size of thearray
in bytes.
std::cout << "Zero-filled array:" << std::endl;
: Outputs a message indicating the zero-filled array is being displayed.for (int i = 0; i < size; ++i) { std::cout << array[i] << " "; }
: Utilizes afor
loop to iterate through each element of thearray
and prints its value followed by a space.std::cout << std::endl;
: Outputs a newline to move to the next line in the output.return 0;
: Indicates successful program execution and terminates themain()
function.