How is dynamic memory allocated for the 2D array in the provided code?

In the provided context, dynamic memory allocation for a 2D array is not explicitly shown. However, you can allocate memory for a 2D array dynamically in C using pointers and the malloc() function. Here's an example of how to do it:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int rows, cols;

    // Get the number of rows and columns
    printf("Enter number of rows: ");
    scanf("%d", &rows);
    printf("Enter number of columns: ");
    scanf("%d", &cols);

    // Allocate memory for an array of pointers (rows)
    int **array = (int **)malloc(rows * sizeof(int *));
    
    // Allocate memory for each row
    for (int i = 0; i < rows; i++) {
        array[i] = (int *)malloc(cols * sizeof(int));
    }

    // Example: Fill the array with values
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            array[i][j] = i * cols + j; // Assign values
        }
    }

    // Print the array
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%d ", array[i][j]);
        }
        printf("\n");
    }

    // Free the allocated memory
    for (int i = 0; i < rows; i++) {
        free(array[i]); // Free each row
    }
    free(array); // Free the array of pointers

    return 0;
}

Explanation:

  1. Allocate Memory for Rows: First, you allocate memory for an array of pointers, where each pointer will point to a row of the 2D array.
  2. Allocate Memory for Columns: Then, for each row, you allocate memory for the columns.
  3. Accessing Elements: You can access elements using array[i][j].
  4. Freeing Memory: Finally, you must free the memory allocated for each row and then free the array of pointers to avoid memory leaks.

0 Comments

no data
Be the first to share your comment!