Does anyone have a way to initialize an array of int
s (any multi-byte type is fine really), to a non-zero and non -1 value simply? By which I mean, is there a way to do this in a one liner, without having to do each element individually:
int arr[30] = {1, 1, 1, 1, ...}; // that works, but takes too long to type int arr[30] = {1}; // nope, that gives 1, 0, 0, 0, ... int arr[30]; memset(arr, 1, sizeof(arr)); // That doesn't work correctly for arrays with multi-byte // types such as int
Just FYI, using memset()
in this way on static arrays gives:
arr[0] = 0x01010101 arr[1] = 0x01010101 arr[2] = 0x01010101
The other option:
for(count = 0; count < 30; count++) arr[count] = 1; // Yup, that does it, but it's two lines.
Anyone have other ideas? As long as it's C code, no limits on the solution. (other libs are fine)
The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.
Solution: This example fill (initialize all the elements of the array in one short) an array by using Array. fill(arrayname,value) method and Array. fill(arrayname ,starting index ,ending index ,value) method of Java Util class.
This is a GCC extension:
int a[100] = {[0 ... 99] = 1};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With