Search⌘ K

Variable Length Arrays

Explore how to declare variable length arrays in C, enabling dynamic memory allocation based on user input or runtime information. Understand the benefits and risks of using arrays without preset sizes, and prepare to manage array sizes efficiently in your programs.

We'll cover the following...

In the array examples earlier, we have hard-coded the size of the array. In modern C, it’s possible to declare arrays without knowing their size until runtime.

Here is how to do it:

C
#include <stdio.h>
int main(void) {
int n;
// We discuss scanf later. For now, note that n holds the input integer.
scanf("%i", &n);
printf("Entered length: %d\n", n);
int grades[n];
int i;
for (i = 0; i < n; i++) {
grades[i] = i;
printf("grades[%d] = %d\n", i, grades[i]);
}
return 0;
}
Did you find this helpful?

We haven’t ...