C array query

Sir, I want to assign 0 in all element of array. for this I write a program.

if x[3]={0} is valid & all of this array element is 0. then in the given below program why error message comes in " int a[j]={0};" as int a[j] comes after assigning value in “j” . why my given below program is not run?

#include <stdio.h>

int main()

{

int i,j;

printf(“Enter the size of array=”);

scanf("%d",&j);

int a[j]={0};

printf(“your Number=”);

for(i=0;i<j;i++)

{

  printf("%d, ",a[i]);

}

return 0;

}

To initialize all array elements to 0, you can do as following.
int a[10] = {};

In both cases, all array elements will be zero.
If you write k elements in bracket, the first k elements will be assigned accordingly and left elements will be assigned with the value zero.
The problem here:- J is not compile time constant that’s why it is showing error.

1 Like

Actually J is not compile time constant. And this type of initialization is done during compile time.

what is compile time constant in c programing ?

j is not known when the compiler is compiling the program, as it is a variable entered by the user. This type of initialization is not supported in C. You can instead run a loop from i=0 to j-1 and set a[i]=0 in the loop.