0

According to C99 standards we can do this

int n = 0;
scanf("%d",&n);
int arr[n];

this is one of the way to create dynamic array in c. Now I want to initialize this array to 0 like this

int arr[n] = {0};

Here my compiler producing error. I want to know can we do this? Is it according to standard? At compile time we provide sufficient memory for arrays, but here it is unknown at compile time. How it is happening?

someone
  • 1,638
  • 3
  • 21
  • 36
  • If you want to have a truly dynamic array that is initialised upon creation use `calloc`. On my GCC compiler the `variable-sized object may not be initialized` error is pretty descriptive of whether this is allowed or not. – Nobilis Jul 05 '13 at 06:15
  • 2
    It is explicitly forbidden to initialize a variable-length array as per constraint 6.7.8/3 "The type of the entity to be initialized shall be an array of unknown size or an object type **that is not a variable length array type**." – dyp Jul 05 '13 at 06:29
  • It would always be helpful to include the text of an error message referenced in the question. – MikeW Jul 12 '17 at 15:56
  • Incidentally, the C99 array is not truly "dynamic" in the sense that its size varies at runtime - its /allocation/ size is determined at runtime, but once allocated, does not change until it goes out of scope. – MikeW Jul 12 '17 at 16:00

2 Answers2

7

can we do this?

No. But you can do this:

int arr[n];
memset(arr, 0, sizeof(arr));

You lose the syntactic sugar for initialization, but you get the functionality.    

MikeW
  • 5,504
  • 1
  • 34
  • 29
0
int n = 0;
scanf("%d",&n);
int arr[n];

You can not do that. If you want allocate memory to an array then use the malloc or calloc functions.

alk
  • 69,737
  • 10
  • 105
  • 255
SANDEEP
  • 1,062
  • 3
  • 14
  • 32