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!
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!
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));
int *array;
int i;
printf ("Amount of numbers to be entered: ");
scanf ("%d",&i);
array = (int*) calloc (i,sizeof(int));
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));
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.