0

Consider the C code below:

#include<stdio.h>
int main()
{int n,i;
scanf("%d",&n); 
int a[n]; //Why doesn't compiler give an error here?
}

How can I declare an array when the compiler doesn't know initially?

6
  • Why do you think it should give you a error? It would be a error in C++, but in C it's not. Commented Oct 29, 2017 at 20:10
  • 3
    Because in the 1999 C standard, it is a valid construct - look up variable length array. It is optional in the 2011 C standard, but compilers are permitted to support it. Commented Oct 29, 2017 at 20:11
  • for the same reason because array initialisation gives an error Commented Oct 29, 2017 at 20:11
  • Can you show the code that gives you the error? Commented Oct 29, 2017 at 20:14
  • 5
    A VLA cannot be initialised using normal array initialisation syntax. That syntax requires the number of elements in the array to be known to the compiler. The whole point of a VLA is that the number of elements is determined at run time (in this case, based on the value of n read by the preceding scanf()). Commented Oct 29, 2017 at 20:17

1 Answer 1

0

When the the exact size of array is unknown until compile time, you need to use dynamic memory allocation. In the C standard library, there are functions for dynamic memory allocation: malloc, realloc, calloc and free.

These functions can be found in the <stdlib.h> header file.

If you want to create an array you do:

int array[10];

In dynamic memory allocation you do:

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

In your case is:

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

If you allocate a memory position, never forget to deallocate:

if(array != NULL)
  free(array);

Memory allocation is a complex subject, I suggest you search for the subject because my answer was simple. You can start with this link:

https://www.programiz.com/c-programming/c-dynamic-memory-allocation

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

1 Comment

"When the the exact size of array is unknown until compile time" -- did you mean unknown until run-time? In any case, this is wrong. Variable length arrays were introduced into Standard C with C99. Though they were made optional with C11, they are still widely supported and available.

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.