C Program: Dynamically Allocate 2D Array of Integers

16 Dec 2022 Balmiki Mandal 0 C Programming

C Program for Runtime 2D Array Creation with Dynamic Memory

To allocate dynamic memory for a 2D array of integers where the number of rows and columns are scanned from the user at runtime in C, you can use the following steps:

  1. Declare a pointer to a pointer to an integer. This will be the pointer to the 2D array.
  2. Prompt the user to enter the number of rows and columns.
  3. Allocate memory for the number of rows using the malloc() function.
  4. For each row, allocate memory for the number of columns using the malloc() function.
  5. Assign the addresses of the allocated memory to the pointer to the 2D array.

C program implements the above steps:

C Programming
#include 
#include 

int main() {
  // Declare a pointer to a pointer to an integer
  int **array;

  // Prompt the user to enter the number of rows and columns
  int rows, columns;
  printf("Enter the number of rows: ");
  scanf("%d", &rows);
  printf("Enter the number of columns: ");
  scanf("%d", &columns);

  // Allocate memory for the number of rows
  array = (int **)malloc(rows * sizeof(int *));

  // For each row, allocate memory for the number of columns
  for (int i = 0; i < rows; i++) {
    array[i] = (int *)malloc(columns * sizeof(int));
  }

  // Initialize the 2D array
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < columns; j++) {
      array[i][j] = 0;
    }
  }

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

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

  return 0;
}

Example output:

 

Enter the number of rows: 3
Enter the number of columns: 4

0 0 0 0
0 0 0 0
0 0 0 0

Further Reading:


2D Dimensional Array in c programming

Write a C Program to reverse 2D array Elements

Integer 2D array Passing to function in c

String 2D array to a Function in c

Write a C program to short 2D array using bubble sort

c program to allocate dynamic memory for 2D array integers

Using Arrays of Pointers to Represent Two-Dimensional Arrays

How to Calculate of sub element of 2D array and How to print it in c

Write a C Program to scan 5 Elements and print on the screen using 2D array

Assingement of 2D array in c

Enroll Now:

C-Programming From Scratch to Advanced 2023-2024] "Start Supercharging Your Productivity!"

Contact Us:

  • For any inquiries, please email us at [[email protected]].
  • Follow us on insta  [ electro4u_offical_ ] for updates and tips.

 

Note: If you encounter any issues or specific errors when running this program, please let me know and I'll be happy to help debug them!

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.