Ask Your Question
0

How can a 2D array be created using dynamic memory allocation?

asked 2023-05-29 23:26:26 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-05-29 23:38:01 +0000

scrum gravatar image

Here is an example of how to create a 2D array using dynamic memory allocation in C++:

int rows = 5;
int columns = 3;

// Allocate memory for rows
int** arr = new int*[rows];

// Allocate memory for columns for each row
for (int i = 0; i < rows; i++) {
    arr[i] = new int[columns];
}

// Initialize values
for (int i = 0; i < rows; i++) {
    for (int j = 0; j < columns; j++) {
        arr[i][j] = i + j;
    }
}

// Access values
for (int i = 0; i < rows; i++) {
    for (int j = 0; j < columns; j++) {
        std::cout << arr[i][j] << " ";
    }
    std::cout << std::endl;
}

// Free memory
for (int i = 0; i < rows; i++) {
    delete[] arr[i];
}
delete[] arr;

In this example, we allocate memory for rows number of pointers using new int*[rows]. We then use a loop to allocate memory for columns number of integers for each row using new int[columns]. We can then access and modify values using the row and column indices. Finally, we must free the memory allocated for each row and the pointer to the array using delete[].

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-29 23:26:26 +0000

Seen: 14 times

Last updated: May 29 '23