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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
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.