2

Is there any way to assign all elements of an array the value 0 in one go.The array accepts its size from the user. Hence

int array[x] = {0};

Won't work!

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
nebula
  • 51
  • 4

4 Answers4

0

You will need to dynamically allocate the memory for this array:

int *array;
int x;

scanf("%d\n", &x);

array = malloc(sizeof(int) * x);

then set value for all of them

memset(array, 0, x);

or use calloc:

array = calloc(x, sizeof(int));
Mauren
  • 1,955
  • 2
  • 18
  • 28
0
int *array;
int i;
printf ("Amount of numbers to be entered: ");
scanf ("%d",&i);

array = (int*) calloc (i,sizeof(int));
CS Pei
  • 10,869
  • 1
  • 27
  • 46
0

Use memset

void * memset ( void * ptr, int value, size_t num );

int *array = (int *) malloc(sizeof(int) * x);

memset(array,0,sizeof(int) * x);

OR Use:

void* calloc (size_t num, size_t size);

int *array = (int *) calloc(x, sizeof(int));
Steven Eckhoff
  • 992
  • 9
  • 18
0

My best bet is to use memset from string.h library.

memset(array,0,x*sizeof(int));

This is not technically initialization, because there is no assignment, it only sets all bytes in given memory to '0' but that's exactly what you want to do here.
Also, consider using malloc for creating your array, because the way you do it now, your array will be created on the stack(which has finite capacity) and will be freed when function that creates it returns(just like regular automatic variable). That means your array is inaccessible from outside of its local scope.

zubergu
  • 3,646
  • 3
  • 25
  • 38