Knowee
Questions
Features
Study Tools

Which of the following is the correct way to dynamically allocate memory for a 2D array in C?int **arr = malloc(rows * cols * sizeof(int));int *arr = malloc(rows * sizeof(int*));int **arr = malloc(rows * sizeof(int*)); for (int i = 0; i < rows; i++) arr[i] = malloc(cols * sizeof(int));int **arr = malloc(rows * sizeof(int)); for (int i = 0; i < rows; i++) arr[i] = malloc(cols);

Question

Which of the following is the correct way to dynamically allocate memory for a 2D array in C?int **arr = malloc(rows * cols * sizeof(int));int arr = malloc(rows * sizeof(int));int *arr = malloc(rows * sizeof(int)); for (int i = 0; i < rows; i++) arr[i] = malloc(cols * sizeof(int));int **arr = malloc(rows * sizeof(int)); for (int i = 0; i < rows; i++) arr[i] = malloc(cols);

🧐 Not the exact question you are looking for?Go ask a question

Solution

The correct way to dynamically allocate memory for a 2D array in C is:

int **arr = malloc(rows * sizeof(int*)); 
for (int i = 0; i < rows; i++) 
    arr[i] = malloc(cols * sizeof(int));

Here's why:

  1. int **arr = malloc(rows * sizeof(int*)); This line is allocating memory for 'rows' number of pointers to int. Each pointer will later point to the first element of each row.

  2. for (int i = 0; i < rows; i++) arr[i] = malloc(cols * sizeof(int)); This loop is allocating memory for 'cols' number of integers for each row.

So, in total, you have a dynamically allocated 2D array.

This problem has been solved

Similar Questions

How is memory allocated for an array dynamically in C++?int* arr = new int[10];int arr = new int[10];int arr[10] = new int;int* arr = alloc int[10];

To allocate enough space for an array of 10 integers (on a 64bit, Linux machine), I can use:malloc(64 * 10)malloc(10 * int)malloc(10 * sizeof(int))

Stuart is working on a program to manage arrays. Given an initial array size and elements, the program resizes the array to twice its original size and fills the additional places with the same original elements. Write a program to help Stuart dynamically allocate the memory for the array using malloc(), and then resize using realloc(), and then print the elements of the resized array.Input format :The first line of input consists of an integer N, representing the initial size of the array.The second line consists of N space-separated integers, representing the initial elements of the sequence.

What is the correct way to declare a 2D array in C?

How do you initialize a 2D array in C?

1/3

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.