I'm a beginner with C and I'm trying to learn how to work with dynamic allocation of 2D matrixes. Can someone tell me why it gives me problems? (In the main function, I used 10 and 11 as test sizes.)
#include <stdio.h>
#include <stdlib.h>
void insert_values(int **arr, int dim, int size);
void resize(int ***arr, int dim) {
if (*arr == NULL) {
*arr = (int **)malloc(dim * sizeof(int *));
if (!*arr) return;
}
else {
*arr = (int **)realloc(*arr, dim * sizeof(int *));
if (*arr == NULL) return;
}
for (int i = 0; i < dim; i++) {
if ((*arr)[i] == NULL) {
(*arr)[i] = (int *)malloc(dim * sizeof(int));
if (!(*arr)[i]) return;
break;
}
else { //se esiste la posizione allora lo rialloco
(*arr)[i] = (int *)realloc(**arr, dim * sizeof(int));
if ((*arr)[i] == NULL) return;
}
}
}
void insert_values(int **arr, int dim, int size) {
if (size > dim) {
resize(&(arr), size);
}
int x;
int y;
for(x = 0; x < size; x++) {
for (y = 0; y < size; y++) {
arr[x][y] = x + y;
printf("%d |", arr[x][y]);
}
printf("\n");
}
}
void print_values(int **arr, int size) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
printf("%d |", *(arr+i)[j]);
}
printf("\n");
}
}
int main(int argc, char *argv[]) {
int **x = (int**)malloc(10 * sizeof(*x));
if (!x) { return 0; }
for (int i = 0; i < 10; i++) {
x[i] = (int*)malloc(10 * sizeof(int));
}
insert_values(x, 10, 11);
print_values(x, 11);
for (int i = 0; i < 10; i++) {
free(x[i]);
}
free(x);
}
0 |1 |2 |3 |4 |5 |6 |7 |8 |9 |10 |
1 |2 |3 |4 |5 |6 |7 |8 |9 |10 |11 |
2 |3 |4 |5 |6 |7 |8 |9 |10 |11 |12 |
3 |4 |5 |6 |7 |8 |9 |10 |11 |12 |13 |
4 |5 |6 |7 |8 |9 |10 |11 |12 |13 |14 |
5 |6 |7 |8 |9 |10 |11 |12 |13 |14 |15 |
6 |7 |8 |9 |10 |11 |12 |13 |14 |15 |16 |
7 |8 |9 |10 |11 |12 |13 |14 |15 |16 |17 |
8 |9 |10 |11 |12 |13 |14 |15 |16 |17 |18 |
9 |10 |11 |12 |13 |14 |15 |16 |17 |18 |19 |
10 |11 |12 |13 |14 |15 |16 |17 |18 |19 |20 |
-533986992 |-533955728 |
This is the output that during insert_values works but in print_values it gives me a segmentation fault.
Issues with your code have been identified, and it has been suggested that you create an actual
Matrixtype to represent your matrix, rather than having to pass around triple pointers. It may help you to see how this approach would affect your code.