WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

C · Advanced · question 50 of 100

Explain the concept of variable length arrays in C and provide an example.?

📕 Buy this interview preparation book: 100 C questions & answers — PDF + EPUB for $5

Variable length arrays (VLAs) in C are arrays whose size can be determined at runtime rather than at compile time. They were introduced in the C99 standard and are an alternative to dynamic arrays implemented using malloc and pointers.

Here’s an example of using a VLA in C:

    #include <stdio.h>
    
    int main() {
        int size;
        
        printf("Enter the size of the array: ");
        scanf("%d", &size);
        
        int array[size]; // declare a variable length array
        
        // initialize the array elements
        for (int i = 0; i < size; i++) {
            array[i] = i * i;
        }
        
        // print the array elements
        printf("Array elements:n");
        for (int i = 0; i < size; i++) {
            printf("%d ", array[i]);
        }
        printf("n");
        
        return 0;
    }

In this example, we first prompt the user to enter the desired size of the array, which we read into size using scanf. We then declare an array called array of size size using square brackets and the value of size.

We then use a for loop to initialize the array elements to the square of their index. Finally, we print out the array elements using another for loop.

Note that VLAs in C can be a useful tool for writing code that requires dynamic array allocation. However, they also have some limitations and potential issues, such as the potential for stack overflow if the array size is too large, and the lack of portability across different compilers and platforms. As with any language feature, it’s important to use VLAs judiciously and carefully in order to avoid potential issues and pitfalls.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic C interview — then scores it.
📞 Practice C — free 15 min
📕 Buy this interview preparation book: 100 C questions & answers — PDF + EPUB for $5

All 100 C questions · All topics