Assigning a zero to all array elements in C -
in program i'm working on, particular operation not going bottleneck, did me thinking. answers questions such this one , this one i've learned 2 ways (efficiently) set elements of array 0 in c:
double myarray[3]; static const double zeroes[3] = {0}; memcpy(myarray, zeroes, sizeof(zeroes));
and
double myarray[3]; memset(myarray, 0, numberofelementsinmyarray * sizeof(myarray[0]));
before move onto real question: i'm not entirely sure based on the information i've read, assume method would, @ least in principle, fill array int
zeroes (well, unsigned char
's these seem equivalent). correct? if so, explicit conversion of int
zeroes double
zeroes necessary or done implicitly if myarray
declared array of double
's?
anyway, real question this: if array isn't big @ (like myarray
i've declared above), either of these methods still preferred on little loop? if have few arrays of same small size need assigned zeroes? if commented properly, think readability factor in decision , favours particular solution?
just entirely clear: not looking initialize array zeroes.
if it's small array (like 3 elements), won't make difference whether use mem*
functions, or loop, or 3 distinct assignments. in fact, latter case may faster you're not suffering cost of function call:
myarry[0] = myarray[1] = myarray[2] = 0;
but, if 1 is faster, difference not worth worrying about. tend optimise readability first then, if needed, optimise space/storage later.
if choice between memcpy
, memset
, i'd choose latter (assuming, seems case, all-zero bit pattern represented 0.0
in implementation) 2 reasons:
- it doesn't require storage of zeroed array; and
- the former trouble if change size of 1 array , forget other.
and, it's worth, memset
solution doesn't need have multiplication. since can size of entire array, can do:
memset (myarray, 0, sizeof (myarray));
@admin
ReplyDeletehow C language work and what is process of doing array code
Regards,
Deepika Verma