Arrays in C #138121
-
BodyQuestion:How do you dynamically allocate a 2D array in C, and what are the common pitfalls when working with dynamically allocated multi-dimensional arrays? Specifically, consider the following requirements:
Provide a code example that demonstrates the correct memory allocation, usage, and deallocation, and explain any potential issues or mistakes programmers commonly make when working with such arrays. Guidelines
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
To dynamically allocate a 2D array in C with dimensions n x m, where both n and m are provided at runtime, you can use the following steps:
Common Pitfalls:
Below is a code example demonstrating the correct way to dynamically allocate, use, and free a 2D array. #include <stdio.h>
#include <stdlib.h>
// Function to allocate memory for a 2D array
int **allocate_2d_array(int n, int m) {
int **array = malloc(n * sizeof(int *)); // Allocate memory for row pointers
if (array == NULL) {
return NULL; // Memory allocation failed
}
for (int i = 0; i < n; i++) {
array[i] = malloc(m * sizeof(int)); // Allocate memory for each row
if (array[i] == NULL) {
// If allocation fails, free already allocated memory
for (int j = 0; j < i; j++) {
free(array[j]);
}
free(array);
return NULL;
}
}
return array;
}
// Function to free the memory allocated for the 2D array
void free_2d_array(int **array, int n) {
for (int i = 0; i < n; i++) {
free(array[i]); // Free each row
}
free(array); // Free the array of pointers
}
int main() {
int n = 3, m = 4; // Example dimensions
// Allocate memory for the 2D array
int **array = allocate_2d_array(n, m);
if (array == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
// Use the 2D array (e.g., filling it with values)
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
array[i][j] = i * m + j;
}
}
// Print the 2D array
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
printf("%d ", array[i][j]);
}
printf("\n");
}
// Free the allocated memory
free_2d_array(array, n);
return 0;
} Explanation:
Common Mistakes:
This approach ensures you can dynamically allocate, use, and correctly deallocate a 2D array in C. |
Beta Was this translation helpful? Give feedback.
To dynamically allocate a 2D array in C with dimensions n x m, where both n and m are provided at runtime, you can use the following steps:
Common Pitfalls:
Below is a code example demonstrating the correct way to dynamically allocate, use, and free a 2D array.
Code Example