The Wayback Machine - https://web.archive.org/web/20241005162334/https://www.geeksforgeeks.org/variable-length-arrays-in-c-and-c/
Open In App

Variable Length Arrays (VLAs) in C

Last Updated : 24 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In C, variable length arrays (VLAs) are also known as runtime-sized or variable-sized arrays. The size of such arrays is defined at run-time.

Variably modified types include variable-length arrays and pointers to variable-length arrays. Variably changed types must be declared at either block scope or function prototype scope.

Variable length arrays are a feature where we can allocate an auto array (on stack) of variable size. It can be used in a typedef statement. C supports variable-sized arrays from the C99 standard. For example, the below program compiles and runs fine in C.

Syntax of VLAs in C

void fun(int size)
{
int arr[size];
// code
}

Note: In C99 or C11 standards, there is a feature called flexible array members, which works the same as the above. 

Example of Variable Length Arrays

The below example shows the implementation of variable length arrays in C program

C
// C program to demonstrate variable length array
#include <stdio.h>

// function to initialize array
void initialize(int* arr, int size)
{
    for (int i = 0; i < size; i++) {
        arr[i] = i + 1;
    }
}

// function to print an array
void printArray(int size)
{
    // variable length array
    int arr[size];
    initialize(arr, size);

    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
}

// driver code
int main()
{
    int n;
    printf("Enter the Size: ");
    scanf("%d", &n);
    printArray(n);

    return 0;
}


Output

Enter the Size: 5
1 2 3 4 5

Explanation: The above program illustrate how to create a variable size array in a function in C program. This size is passed as parameter and the variable array is created on the stack memory.



Previous Article
Next Article

Similar Reads

Internal static variable vs. External static variable with Examples in C
The static variable may be internal or external depending on the place of declaration. Both kinds of static variables are stored in initialized data segments. Internal Static Variables Internal Static variables are defined as those having static variables which are declared inside a function and extend up to the end of the particular function. Synt
2 min read
How to Access Global Variable if there is a Local Variable with Same Name in C/ C++?
Local Variable: The variable whose scope lies inside a function or a block in which they are declared. Global Variable: The variable that exists outside of all functions. It is the variable that is visible from all other scopes. We can access global variable if there is a local variable with same name in C and C++ through Extern and Scope resolutio
2 min read
Variable Length Argument in C
Variable length argument is a feature that allows a function to receive any number of arguments. There are situations where we want a function to handle variable number of arguments according to requirement. 1) Sum of given numbers. 2) Minimum of given numbers. and many more. Variable number of arguments are represented by three dotes (...) Below i
3 min read
Why Variable Length Array were Removed in C++?
While historically a feature in the C language, the variable length array is not part of standard C++. This article discusses the C++'s approach to dynamic memory allocation, showing an alternative strategy employed to achieve a similar outcome. Variable Length ArrayThe Array is said to be a variable length array if the size is defined at the runti
3 min read
Variable length arguments for Macros
Like functions, we can also pass variable length arguments to macros. For this we will use the following preprocessor identifiers.To support variable length arguments in macro, we must include ellipses (...) in macro definition. There is also "__VA_ARGS__" preprocessing identifier which takes care of variable length argument substitutions which are
2 min read
Multidimensional Arrays in C - 2D and 3D Arrays
Prerequisite: Arrays in C A multi-dimensional array can be defined as an array that has more than one dimension. Having more than one dimension means that it can grow in multiple directions. Some popular multidimensional arrays are 2D arrays and 3D arrays. In this article, we will learn about multidimensional arrays in C programming language. Synta
10 min read
C | Variable Declaration and Scope | Question 1
Consider the following two C lines int var1; extern int var2; Which of the following statements is correct (A) Both statements only declare variables, don't define them. (B) First statement declares and defines var1, but second statement only declares var2 (C) Both statements declare define variables var1 and var2 Answer: (B) Explanation: See Under
1 min read
C | Variable Declaration and Scope | Question 2
Predict the output #include <stdio.h> int var = 20; int main() { int var = var; printf("%d ", var); return 0; } (A) Garbage Value (B) 20 (C) Compiler Error Answer: (A) Explanation: First var is declared, then value is assigned to it. As soon as var is declared as a local variable, it hides the global variable var.Quiz of this Questi
1 min read
C | Variable Declaration and Scope | Question 3
#include <stdio.h> extern int var; int main() { var = 10; printf("%d ", var); return 0; } (A) Compiler Error: var is not defined (B) 20 (C) 0 Answer: (A) Explanation: var is only declared and not defined (no memory allocated for it) Refer: Understanding “extern” keyword in CQuiz of this Question
1 min read
C | Variable Declaration and Scope | Question 4
#include <stdio.h> extern int var = 0; int main() { var = 10; printf("%d ", var); return 0; } (A) 10 (B) Compiler Error: var is not defined (C) 0 Answer: (A) Explanation: If a variable is only declared and an initializer is also provided with that declaration, then the memory for that variable will be allocated i.e. that variable wi
1 min read
C | Variable Declaration and Scope | Question 6
Output? #include <stdio.h> int main() { int x = 1, y = 2, z = 3; printf(" x = %d, y = %d, z = %d \n", x, y, z); { int x = 10; float y = 20; printf(" x = %d, y = %f, z = %d \n", x, y, z); { int z = 100; printf(" x = %d, y = %f, z = %d \n", x, y, z); } } return 0; } (A) x = 1, y = 2, z = 3 x = 10, y = 20.000000, z
1 min read
C | Variable Declaration and Scope | Question 7
int main() { int x = 032; printf("%d", x); return 0; } (A) 32 (B) 0 (C) 26 (D) 50 Answer: (C) Explanation: When a constant value starts with 0, it is considered as octal number. Therefore the value of x is 3*8 + 2 = 26Quiz of this Question
1 min read
C | Variable Declaration and Scope | Question 8
Consider the following C program, which variable has the longest scope? int a; int main() { int b; // .. // .. } int c; (A) a (B) b (C) c (D) All have same scope Answer: (A) Explanation: a is accessible everywhere. b is limited to main() c is accessible only after its declaration.Quiz of this Question
1 min read
Installing MinGW Tools for C/C++ and Changing Environment Variable
MinGW is a native C/C++ compiler(GCC) which have free distributable import libraries and header files for building native Windows applications. In this tutorial, we are going to install MinGW for C/C++. These are a few steps that we have to perform to successfully install MinGW on our device. How to Install the MinGW Tools for C/C++? Step 1: Go to
3 min read
Why can't a const variable be used to define an Array's initial size in C?
What is an array? An array is a collection of items of the same data type stored at contiguous memory locations. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array). The base value is index
3 min read
Local Variable in C
In C language, a variable declared within a function or a block of code is called a local variable. Local variables are frequently used to temporarily store data in a defined scope where they can be accessed and manipulated. They are stored in the memory stack, Once the function or block of code in which the local variable is declared finishes exec
3 min read
Variable Shadowing in C++
Variable shadowing is a common programming concept where a variable declared in some specific scope takes precedence over a variable with the same name declared in an outer scope. In C++, this can happen when you define a new variable within the function or block that has the same name as a variable declared in the outer scope. Both global and loca
3 min read
C++ Variable Templates
Over the years C++ has undergone advancements to improve its capabilities and coding efficiency. One notable addition in C++14 is the introduction of variable templates. These variable templates allow you to create a group of variables or static data members that can be customized providing flexibility for your code. Variable TemplatesVariable temp
4 min read
How to Count Variable Numbers of Arguments in C?
C supports variable numbers of arguments. But there is no language provided way for finding out total number of arguments passed. User has to handle this in one of the following ways: 1) By passing first argument as count of arguments. 2) By passing last argument as NULL (or 0). 3) Using some printf (or scanf) like mechanism where first argument ha
2 min read
Redeclaration of global variable in C
Consider the below two programs: // Program 1 int main() { int x; int x = 5; printf("%d", x); return 0; } Output in C: redeclaration of ‘x’ with no linkage // Program 2 int x; int x = 5; int main() { printf("%d", x); return 0; } Output in C: 5 In C, the first program fails in compilation, but second program works fine. In C++, b
1 min read
How to print a variable name in C?
How to print and store a variable name in string variable? We strongly recommend you to minimize your browser and try this yourself first In C, there’s a # directive, also called ‘Stringizing Operator’, which does this magic. Basically # directive converts its argument in a string. #include <stdio.h> #define getName(var) #var int main() { int
1 min read
Using a variable as format specifier in C
It is known that, printf() function is an inbuilt library function in C programming language in the header file stdio.h. It is used to print a character, string, float, integer etc. onto the output screen. However, while printing the float values, the number of digits following the decimal point can be controlled by the user. One of the ways to do
1 min read
Why variable name does not start with numbers in C ?
In C, apart from keywords, everything in the C program is treated as Identifier. Identifiers can be the names given to variables, constants, functions, and user-defined data. A variable name can consist of alphabets (upper case, lower case), numbers (0-9), and _ (underscore) character. But the name of any variable must not start with a number. Now
2 min read
Representation of Int Variable in Memory in C++
To understand the Representation of int variable in memory in C/C++ below is the basic program to create a variable and its size. Usually, the value of an int variable is stored in a series of bytes that are represented as the variable's representation as memory. Depending on the hardware and compiler being used, an int variable may be represented
5 min read
Different ways to declare variable as constant in C
There are many different ways to make the variable as constant in C. Some of the popular ones are: Using const KeywordUsing MacrosUsing enum Keyword1. Using const KeywordThe const keyword specifies that a variable or object value is constant and can't be modified at the compilation time. Syntaxconst data_type variable_name = initial_value;ExampleTh
2 min read
How to modify a const variable in C?
Whenever we use const qualifier with variable name, it becomes a read-only variable and get stored in .rodata segment. Any attempt to modify this read-only variable will then result in a compilation error: "assignment of read-only variable". In the below program, a read-only variable declared using the const qualifier is tried to modify: [GFGTABS]
2 min read
Iteration Over std::vector: Unsigned vs Signed Index Variable
When we iterate over a std::vector in C++, we need to choose the right type for the index variable to maintain both the correctness and clarity of our code. A common question arises: Should we use an unsigned or signed integer for the index variable? In this article, we will learn the differences between using unsigned and signed index variables, a
4 min read
C | Arrays | Question 1
Predict the output of below program: #include <stdio.h> int main() { int arr[5]; // Assume that base address of arr is 2000 and size of integer // is 32 bit arr++; printf("%u", arr); return 0; } (A) 2002 (B) 2004 (C) 2020 (D) lvalue required Answer: (D) Explanation: Array name in C is implemented by a constant pointer. It is not pos
1 min read
C | Arrays | Question 2
Predict the output of below program: #include <stdio.h> int main() { int arr[5]; // Assume base address of arr is 2000 and size of integer is 32 bit printf("%u %u", arr + 1, &arr + 1); return 0; } (A) 2004 2020 (B) 2004 2004 (C) 2004 Garbage value (D) The program fails to compile because Address-of operator cannot be used with a
1 min read
C | Arrays | Question 4
Output of following program? #include<stdio.h> int main() { int a[] = {1, 2, 3, 4, 5, 6}; int *ptr = (int*)(&a+1); printf("%d ", *(ptr-1) ); return 0; } (A) 1 (B) 2 (C) 6 (D) Runtime Error Answer: (C) Explanation: &a is address of the whole array a[]. If we add 1 to &a, we get “base address of a[] + sizeof(a)”. And this
1 min read
Practice Tags :