Want to initialize a local one dimensional array. How can I do the same without a loop?
Found from some links that int iArrayValue[25]={0};
will initialize all the elements to ZERO. Is it?
If yes then can we write below code to initialize the elements to a non-ZERO value?
int iArrayValue[25]={4};
Do we have some other way to initialize an array to a non-ZERO value?
memset can help us to initialize the element to ZERO.
I'm not sure it's possible without some sort of loop. Even = {0} is (usually, see PS) using a loop behind the scenes, so I assume you mean without using an explicit loop?
So if you have some sort of aversion to vectors, you can use the std::fill algorithm?
PS I think for very small arrays, the compiler will just set the memory to zero directly (by treating it as an int or whatever.) But under the debugger you can see that this code (for not so small arrays)
int iArrayValue[1024]={4}; only meant to set the first element to 4.
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
int main()
{
constint arr_size = 10;
int arr[arr_size] = {1,2,3}; // set the first three elements to 1,2,3 and zero the rest
int arr2[arr_size] = {}; // zero all element [C++]
for(int count = 0; count < arr_size; count++)
{
std::cout << arr[count] << " " << arr2[count] << std::endl;
}
}
In C there are two ways to initialize all elements of an array of a fundamental type. Either you use a loop or you call standard function memset. Without these approaches you can only initialize all elements to zeroes when you are defining an array
for your input.
But I wanted to know how to initialize an array to a constant value without using an explicit loop.
Is there anyway out? For this I want to know how internally below statement int arr2[arr_size] = {}; // zero all element [C++]
is being handled, so that a similar way can be thought of.
My problem is that I need to reset an array at runtime to a non-ZERO +ve value. Currently I am doing this in a for loop. But searching for a better one.