what is the difference between the two

what is the difference between arr[n]={0} and using memset(arr,0,n) according to me both of them initilise the array with 0 is it correct??


there is a lot of difference !!
suppose you do

int array[100] = {-1};

you expect this line to initialize all array elements with -1
but it will not .

this set the first element to -1 and the rest to 0 , since all omitted elements are set to 0 if you specify at least one.

to set them all to -1, you can use something like std::fill_n

std::fill_n(array, 100, -1);

whereas memset will show the expected behaviour .

see this stackoverflow

let me explain this to you in detail .

int arr[n]={0};
this will set all elements to zero .

Elements with missing values will be initialized to 0:

ex :-

int myArray[10] = { 1, 2 }; // initialize to 1,2,0,0,0…

So this will initialize all elements to 0:

int myArray[10] = { 0 }; // all elements 0

In C++, an empty initialization list will also initialize every element to 0. This is not allowed with C:

int myArray[10] = {}; // all elements 0 in C++

Remember that objects with static storage duration will initialize to 0 if no initializer is specified:

static int myArray[10]; // all elements 0

so using the above is better and more portable than memset().


The first one will infinite because just it intialises the array but it does not have ending but in second one it is correct way of ending the loop in arrays

@ acodebreaker2 you mean to say that the arr[n]={0} sets all the n elements equal to specified value(0) but this does not work for other elements like -1

read the edited answer

@acodebreaker2 thanks a lot i understood it now thanks !!

welcome @yogeshforyou


Generally it is a misconception that all the elements in the array for int a[100] = {-1} will be -1.

but came to know a new concept.

Awesome explaination!Thank you :slight_smile:

@saiavinashiitr welcome :slight_smile:

@saiavinashiitr thanks

@saiavinashiitr thanks