initialising every elements of an array to 0 in c

,

At the time of declaration i can initialize every elements of an array to ‘0’ in C using calloc() or statements like :

int a[10]={0};

but I want to reset all the elements to ‘0’ after every iteration of a loop.
Can it be done without declaring the array again? (In the example statement above I am declaring the array too)

I am just looking for the fastest possible way of initializing all the elements of an array to zero.

simply use for loop or memset, there is no magic construction to achieve the same…

2 Likes

obviously loop can be used but i needed something which would consume lesser time. memset seems good. thanks :slight_smile:

What did you mean by “without declaring the array again”? If that didn’t mean declaring the array inside the loop, then you can try that as well.

Something like this:

int main()
{
    ...
    while (t--)
    {
        int arr[] = {0};
        ...
    }
    ...
}

And do forget about this, if this is what you meant!! :slight_smile:

2 Likes

If you are facing TLE problem, then memset won’t help probably…

By “without declaring the array again”, I mean that using “int a[10]={0}” will initialize all elements to zero but it will also re-declare the array. I don’t need to declare the array again. I am just looking for the fastest possible way of initializing all the elements of an array to zero.

I am not facing TLE problem. I am just looking for the fastest possible way of initializing all the elements of an array to zero.

int a[n]={0}; also take O(n) time to initilise…it doesnt affect running time to much whether ur initilising by foor-loop,or memset or int a[n]={0}; although there are some crazy techniques which can initilise an array in O(1) time. but not worth implementing in contests.

2 Likes

memset() gives TLE sometimes on codechef

what do u mean is there anything wrong with codechef or memset

@princerk, i think there is sth wrong with codechef. last month’s long challenge easiest question gave TLE, just becuase of memset(). thank God, sb discussed it on forum and then i realized the reason of TLE and changed it with for loop and got AC, though memset() was faster. admins here horrible, i am pretty sure that they havent fixed that bug yet. for comparison: http://stackoverflow.com/questions/7367677/is-memset-more-efficient-than-for-loop-in-c.

//