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?

4
  • 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. Commented Jul 5, 2013 at 6: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." Commented Jul 5, 2013 at 6:29
  • It would always be helpful to include the text of an error message referenced in the question. Commented Jul 12, 2017 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. Commented Jul 12, 2017 at 16:00

2 Answers 2

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.    

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

V(ariable)L(ength)A(array)s came with C99.
You talkin' to me?<tm> @H2CO3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.