ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Programming Fundamentals
    CC-112
    Progress0 / 39 topics
    Topics
    1. Introduction to Problem Solving, Algorithms, Programming, and C Language2. Problem Solving, a brief review of Von-Neumann Architecture3. The C Programming Language, Pseudo-code, Concept of Variable4. Data types in Pseudo-code, The C Standard Library and Open Source5. Input/Output, Arithmetic expressions, Assignment statement, Operator precedence6. Concept of Integer division, Flowchart and its notations7. Typical C Program Development Environment, Role of Compiler and Linker8. Test Driving C Application9. Introduction to C Programming: A Simple C Program: Printing Text, Adding Two Integer10. Memory Concepts, Arithmetic in C, Operators11. Decision Making: Equality and Relational Operators12. Structured Program Development: The if, if...else, while Nested Control Statements13. Program Control: for, switch, do...while, break, continue, Logical Operators14. Functions: Modularizing Program in C, Math Library Functions15. Function Definitions and Prototypes, Function-Call Stack and Stack Frames16. Stack rolling and unrolling, Headers, Passing Arguments by Value and by Reference17. Random Number Generation, Scope Rules, Recursion, Recursion vs Iteration18. Arrays: Defining Arrays, Character Arrays, Static and Automatic Local Arrays19. Passing Arrays to Function, Sorting and Searching Arrays20. Multidimensional and Variable Length Arrays21. Pointers: Pointer Definitions and Initialization, Pointer Operators22. Passing Arguments to Function by Reference, Using the const and sizeof Operator23. Pointer Expressions and Arithmetic, Pointers and Arrays, Array of Pointers24. Function Pointers25. Characters and Strings: Strings and Characters, Character Handling Library26. String Functions, Library Functions27. Formatted Input/Output: Streams, Formatted Output with printf, Formatted Input with scanf28. Structures: Defining Structures, Accessing Structure Member, Structures and Functions29. typedef, Unions30. Bit Manipulation and Enumeration: Bitwise Operators, Bit Fields, Enumeration Constants31. File Processing: Files and Streams, Creating, Reading and Writing data to a Sequential and a Random-Access File32. Preprocessor: #include, #define, Conditional Compilation, #error and #pragma33. # and ## Operators, Predefined Symbolic Constants, Assertions34. Other Topics: Variable Length Argument List, Using Command Line Arguments35. Compiling Multiple-Source-File Programs, Program Termination with exit and atexit36. Suffixes for Integer and Floating-Point Literals, Signal Handling37. Dynamic Memory Allocation: calloc and realloc, goto38. Advance Topics: Self-Referential Structures, Linked Lists39. Efficiency of Algorithms, Selection and Insertion Sort
    CC-112›Multidimensional and Variable Length Arrays
    Programming FundamentalsTopic 20 of 39

    Multidimensional and Variable Length Arrays

    7 minread
    1,155words
    Intermediatelevel

    Multidimensional and Variable Length Arrays in C

    In C programming, arrays can be of more than one dimension, allowing you to represent more complex data structures, like matrices or tables. Additionally, C allows Variable Length Arrays (VLAs), which are arrays whose size is determined at runtime rather than compile time.

    Let’s explore both Multidimensional Arrays and Variable Length Arrays in detail.


    1. Multidimensional Arrays in C

    A multidimensional array is an array of arrays. The most common type is a two-dimensional array, but arrays can have more than two dimensions. These arrays are useful for representing data in table-like formats, such as matrices or grids.

    Defining Multidimensional Arrays

    A two-dimensional array can be thought of as a table with rows and columns. The general syntax to declare a 2D array is:

    type arrayName[rowCount][columnCount];
    

    For higher-dimensional arrays, you simply add more dimensions in the declaration.

    Example: Declaring a Two-Dimensional Array

    #include <stdio.h>
    
    int main() {
        // Declaring a 2D array (3 rows and 4 columns)
        int matrix[3][4] = {
            {1, 2, 3, 4},
            {5, 6, 7, 8},
            {9, 10, 11, 12}
        };
    
        // Printing the array elements (matrix)
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 4; j++) {
                printf("%d ", matrix[i][j]);
            }
            printf("\n");
        }
    
        return 0;
    }
    

    Explanation:

    • The array matrix is a 2D array with 3 rows and 4 columns.
    • The elements are printed row by row using two for loops: one for the rows and one for the columns.

    Output:

    1 2 3 4 
    5 6 7 8 
    9 10 11 12
    

    Accessing Elements in a Multidimensional Array:

    • To access a specific element, you use two indices: one for the row and one for the column.

    For example, to access the element at the second row and third column:

    int element = matrix[1][2];  // Remember, arrays are 0-indexed
    

    Higher-Dimensional Arrays:

    You can define arrays with more than two dimensions as well. For example, a three-dimensional array:

    int threeD[2][3][4];  // A 3D array with 2 layers, 3 rows, and 4 columns
    

    The syntax is similar, but it requires an extra pair of square brackets for each additional dimension.


    2. Variable Length Arrays (VLAs)

    A Variable Length Array (VLA) is an array in which the size is not known at compile-time but is determined at runtime. This means the size of the array is provided by the user or another part of the program during execution.

    VLAs are supported in C99 and later versions of the C standard. They allow for more flexible programs, especially when dealing with dynamic data.

    Syntax:

    type arrayName[size];
    

    Here, size is determined at runtime, making the array's size dynamic.

    Example: Using a VLA

    #include <stdio.h>
    
    int main() {
        int n;
        printf("Enter the number of elements: ");
        scanf("%d", &n);
    
        // Declare a variable length array
        int arr[n];  // Array size determined at runtime
    
        // Populate the array
        for (int i = 0; i < n; i++) {
            arr[i] = i + 1;  // Assigning values 1 to n
        }
    
        // Print the array
        for (int i = 0; i < n; i++) {
            printf("%d ", arr[i]);
        }
    
        return 0;
    }
    

    Explanation:

    • The user is prompted to input the number of elements n.
    • A VLA arr is created with a size of n (which is determined at runtime).
    • The array is populated with values from 1 to n, and then the values are printed.

    Output Example:

    Enter the number of elements: 5
    1 2 3 4 5
    

    Key Points about VLAs:

    1. Size Determined at Runtime: The size of the array is decided during the program’s execution rather than at compile time.
    2. Memory Allocation: The memory for VLAs is allocated on the stack. However, they can only be used inside the function they are declared in.
    3. Limitations: While VLAs provide flexibility, they can cause issues if the array is too large to fit on the stack (which is generally limited in size), potentially leading to a stack overflow. For very large arrays, dynamically allocated memory (using malloc or calloc) may be more appropriate.

    3. Comparison Between Fixed Size Arrays and Variable Length Arrays

    Feature Fixed Size Array Variable Length Array (VLA)
    Size Determination Size is determined at compile time. Size is determined at runtime.
    Memory Allocation Allocated on the stack or statically. Allocated on the stack.
    Flexibility Less flexible, fixed size. More flexible, can vary depending on user input.
    Scope Scope is determined by the variable's scope. Scope is determined by the variable’s scope.
    Portability Always works, since the size is fixed. Requires a compiler that supports C99 or later.

    4. Use Cases of Multidimensional and VLAs

    Multidimensional Arrays:

    • Matrices: Used in mathematical problems involving matrices (e.g., matrix multiplication).
    • Tables: Storing tabular data, such as database tables or spreadsheets.
    • Grids: Representing game boards (e.g., tic-tac-toe, chess) or 2D maps.

    Variable Length Arrays (VLAs):

    • Dynamic Data Handling: Useful when the size of the data is unknown at compile time and depends on user input or other runtime conditions.
    • Memory Efficiency: If the size of the array is large and depends on dynamic conditions, using VLAs can avoid allocating unnecessary memory, compared to predefining the array size at compile time.

    5. Key Differences Between Multidimensional Arrays and Variable Length Arrays

    Feature Multidimensional Arrays Variable Length Arrays (VLAs)
    Dimensionality Arrays with multiple dimensions (2D, 3D, etc.) Arrays with variable size determined at runtime
    Size Determination Size must be determined at compile time (except for VLA's 1D) Size is determined at runtime, making it more flexible
    Memory Allocation Static, allocated on stack (fixed size) Dynamic, allocated on stack, can vary at runtime
    Usage Used for matrices, grids, and tables Used when the array size is not known until runtime

    Conclusion

    1. Multidimensional Arrays:

      • A fundamental concept for representing tables, matrices, and grids.
      • Can have two or more dimensions, allowing complex data representation.
      • Are statically sized and require the dimensions to be known at compile time.
    2. Variable Length Arrays (VLAs):

      • Provide dynamic sizing, allowing the array size to be determined during execution.
      • Useful in cases where the array size can’t be known beforehand, such as user input-driven scenarios.
      • Available in C99 and later, but they can be risky for very large arrays due to stack size limitations.

    Both multidimensional and variable-length arrays are important for managing complex and dynamic data in C, and understanding when and how to use them efficiently will improve your ability to write flexible and efficient C programs.

    Previous topic 19
    Passing Arrays to Function, Sorting and Searching Arrays
    Next topic 21
    Pointers: Pointer Definitions and Initialization, Pointer Operators

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time7 min
      Word count1,155
      Code examples0
      DifficultyIntermediate