### using realloc for 2D array

uhu ! ... another beginer here !

What I'm doing wrong ?
Using this combination of c1, r1, c2, r2, it's stops on line 36
Normally, should work for any combination

 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162`` ``````#include #include #include #include int main() // Define matrix as an array of pointers { int** xyz; int r1=3, c1=2 , r2=2 , c2=3 ; int i, j; // Allocate the columns xyz = (int**)calloc(c1, sizeof(int*)); // Allocate the rows for (i = 0; i < r1; i++) xyz[i] = (int*)calloc(r1, sizeof(int)); // Initialize the element(s) for(i = 0; i < r1; i++) for(j = 0; j < c1; j++) xyz[i][j] = (i*j+i*i); // Display whole matrix for(i = 0; i < r1; i++) { putchar('\n'); for(j = 0; j < c1; j++) printf("%i\t", xyz[i][j]); } // Increase number of row(s) and column(s) putchar('\n'); // Reallocate columns xyz = (int**)realloc(xyz, (c1 + c2)*sizeof(int*)); // The new column's pointer must be initialised to NULL for(i = c1; i < (c1 + c2); i++) xyz[i] = NULL; // Reallocate rows for (i = r1; i < (r1 + r2); i++) xyz[i] = (int*)realloc(xyz[i], (r1 + r2)*sizeof(int)); // Display whole matrix for(i = 0; i < (r1 + r2); i++) { putchar('\n'); for(j = 0; j < (c1 + c2); j++) printf("%d\t", xyz[i][j]); } // Deallocate the rows for (i = r1 ; i < (r1 + r2) ; ++i) free(xyz[i]); // Deallocate the columns free(xyz); return(0); }``````

thank you !
Last edited on
you mistake c and r.

On line 13 you allocate enough space for c1, but on line 16 you initialize it with r1. All other loops follow the same mistake
yep, thank you for your help !

Topic archived. No new replies allowed.