I’m wondering if there is an easier and faster way to do it. I checked online that it is possible to do “array[10]={0}” or “array[10]={ }”, but I tested on codechef compiler for C and it does not work.
Do you know of any other way to do it that works on codechef compiler for C?
Initialising an array can be done in the following way:
int a[100];
// a[0] will be some garbage value, but rest all will be 0's.
/*
Initialising with 0
*/
// Static way of initialisation
int a[100] = {0}; // all elements will be 0
// Or use #define to define the size of array.
#define size 10000
int b[size] = {0}; // All elements will be 0 in this case too
// The following doesn't work
int n = 100;
int c[n] = {0}; // error: variable-sized object may not be initialized
/*
Initialising with some other value (say 15)
*/
// The following doesn't work
int a[100] = {15}; // a[0] will be 15, but rest all values will be 0
// Use for loop to initialise
int a[100];
for(int i=0;i<100;i++)
a[i] = 15;
// Initialisation won't affect the time complexity, since O(n) loops are lightning fast in C.
here all the elements of the array will be initialized to 0
you can also set the number of bytes you want to initialize (from the starting of the array)
something like this
memset(array, 0, n * sizeof(arr[0]));
will initialize first n elements to 0
note-> you have to add the header <memory.h> or <string.h> in order to use memset function!
Thank you suman_18733097, I tested each example and worked exactly as you mentioned. Thanks for your contribution. I think I was having problem with variable sized array.
Thank you for the help, eraldo_coil. It also works for variable sized arrays. That is cool. Thanks for your contribution.
I noticed that it does not work with values different than zero in the second argument of the function right? It seems to work with strings, but not with int arrays. I am trying for example: memset(array, 10, n * sizeof(arr[0]));