Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize an array with only -1 values [duplicate]

Tags:

arrays

c

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.

like image 273
patriques Avatar asked Nov 21 '12 16:11

patriques


2 Answers

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);
like image 90
Omkant Avatar answered Sep 16 '22 14:09

Omkant


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;
   }
like image 40
ouah Avatar answered Sep 20 '22 14:09

ouah