Last active
November 22, 2024 17:04
-
-
Save Bloody-Badboy/5222024a22cb663a779049fe83338617 to your computer and use it in GitHub Desktop.
Simple 2d array dynamic memory allocation and reallocation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
#include<stdlib.h> | |
int main() { | |
int row = 5; | |
int col = 5; | |
int **arr2d, y, x; | |
arr2d = (int **) malloc(sizeof(int *) * row); // allocate memory for each row which is pointer to a pointer | |
for (y = 0; y < row; y++) { | |
arr2d[y] = malloc(sizeof(int) * col); // now allocate memory block for each row as one dimension array | |
} | |
// put some values into them | |
for (y = 0; y < row; y++) { | |
for (x = 0; x < col; x++) { | |
arr2d[y][x] = row * y + x; | |
} | |
} | |
// print all the values | |
for (y = 0; y < row; y++) { | |
for (x = 0; x < col; x++) { | |
printf("%5d", arr2d[y][x]); | |
} | |
printf("\n"); | |
} | |
int newRow = 6; | |
int newCol = 6; | |
arr2d = realloc(arr2d, sizeof(int *) * newRow); | |
for (y = 0; y < newRow; y++) { | |
arr2d[y] = realloc(arr2d[y], sizeof(int) * newCol); | |
if (arr2d[y] == NULL) { | |
// TODO: handle memory allocation fail error | |
exit(1); | |
} | |
} | |
// print all the values | |
for (y = 0; y < newRow; y++) { | |
for (x = 0; x < newCol; x++) { | |
printf("%5d", arr2d[y][x]); | |
} | |
printf("\n"); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment