c - How to initialize all members of an array to the same value? -
i have large array in c (not c++ if makes difference). want initialize members same value. swear once knew simple way this. use memset()
in case, isn't there way built right c syntax?
unless value 0 (in case can omit part of initializer , corresponding elements initialized 0), there's no easy way.
don't overlook obvious solution, though:
int myarray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };
elements missing values initialized 0:
int myarray[10] = { 1, 2 }; // initialize 1,2,0,0,0...
so initialize elements 0:
int myarray[10] = { 0 }; // elements 0
in c++, empty initialization list initialize every element 0. not allowed c:
int myarray[10] = {}; // elements 0 in c++
remember objects static storage duration initialize 0 if no initializer specified:
static int myarray[10]; // elements 0
and "0" doesn't mean "all-bits-zero", using above better , more portable memset(). (floating point values initialized +0, pointers null value, etc.)
Comments
Post a Comment