int main(){
int ar[50]={1};
//OR
int br[50];
memset(br, 1, sizeof(br));
return 0;
}

- 8,558
- 4
- 35
- 43

- 13
- 3
-
1ar[50]={1}; only sets the first value in the array to 1, not the entire array contents – auburg Jun 17 '20 at 12:32
-
1Does this answer your question? [Can I initialize an STL vector with 10 of the same integer in an initializer list?](https://stackoverflow.com/questions/10237751/can-i-initialize-an-stl-vector-with-10-of-the-same-integer-in-an-initializer-lis) – Nick is tired Jun 17 '20 at 14:27
2 Answers
suppose you do
int ar[50] = {-1};
Now you will expect this line to initialize all array elements with -1 but it will not. It will only set the first element of array to -1 and rest to 0. Whereas memset will show the expected behaviour.
See this Initialization of all elements of an array to one default value in C++? for more info.
let's take an example:-
int arr[5] = { 1, 2 }; // this will initialize to 1,2,0,0,0
int ar[5] = { }; // this will initialize all elements 0
int myArray[10] = {}; // his will also all elements 0 in C++ not in c
So If you want to initialize a specific value to an array use memset().
If you want to initialize all elements in an array to 0 use
static int myArray[10]; // all elements 0
Because objects with static storage duration will initialize to 0 if no initializer is specified and it is more portable than memset().
Also, The int ar[50]={0};
will be infinite because it just initializes the array and does not have an ending but in memset(arr,0,sizeof(br))
it has the correct way of ending the loop in arrays

- 2,726
- 3
- 18
- 38
int ar[50]={1};
This will set only the first element to 1
. Rest all will be 0
.
memset(br, 1, sizeof(br));
This will set all the bytes in br
to 1. It is not the same as setting all the values to 1
. The values afterwards are:
{16843009, 16843009, 16843009, 16843009, 16843009}
Use memset
when you know you really need it. It is not exactly made for initializing arrays, it just set the memory to a particular value.
Best way in C++? Use std::fill
or std::fill_n
.
Example:
int array[5];
std::fill(array, array + 5, 8);
Array now contains:
{8, 8, 8, 8, 8}
Using fill_n
std::fill_n(array, 5, 99);
Array now contains:
{99, 99, 99, 99, 99}
As a side note, prefer using std::array
instead of c-style arrays.
Try on godbolt: https://godbolt.org/z/DmgTGE
References:
[1] : Array Initialization
[2] : memset doc

- 8,558
- 4
- 35
- 43