Possible Duplicate:
How to initialize an array in C
initializing an array of ints
I wonder over the fastest/simplest way to initialize an int array to only contain -1 values. The array I need is 90 ints long so the straightforward way should be to initialize it like this:
int array[90]={-1, -1, -1, ...};
but I only want to use the array once so I want to be able to use it dynamically and be able to free it after using it in the program, so Im more looking for a fast way like calloc
, but instead of zeros, -1 of course.
If you are using gcc then use designated initializer
int array[90] = { [ 0 ... 89 ] = -1}
int array[90],i;
for(i = 0; i < 90 ; arr[i++] = -1);
To do this dynamically , you will have to allocate using malloc
then you only free the memory, otherwise freeing the memory which is not allocated by malloc
, calloc
or realloc
is undefined behavior.
Use this:
int *array;
array=malloc(sizeof(int)*n);
for(i=0;i<n;array[i++]=-1);
// After use free this
free(array);
It is not possible to do it in Standard C at initialization without explicitly enumerating all initializers.
In GNU C you can use GNU C designated initializers
int array[90] = {[0 ... sizeof array - 1] = -1};
after initialization:
int i;
for (i = 0; i < sizeof array / sizeof *array; i++)
{
array[i] = -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