c - Field within structure take random values -
i'm new c , i'm trying define matrix using struct , methods change int** field of struct. matrix supposed dynamically allocated , resizable in how many rows can have. when run program below , print out values of matrix in main, matrix have random values, not ones inserted in genmatrix() , addrow(). doing wrong? grateful help.
i define struct this:
typedef struct matrix { int** matrix; int rows; int cols; int capacity; } matrix;
and have following methods should change field of struct:
matrix* genmatrix() { matrix* matrix = malloc(sizeof(matrix)); initmatrix(matrix, 100, 3, 200); (int = 0; < 10; i++) { (int j = 0; j < 10; j++) { int row[] = {i+j, i*j, i-j}; addrow(matrix, row); } } return matrix; } void initmatrix(matrix* matrix, int rows, int cols, int capacity) { matrix->matrix = malloc(rows * sizeof(int*)); (int = 0; < rows; i++) { matrix->matrix[i] = malloc(cols * sizeof(int)); } matrix->cols = cols; matrix->rows = rows; matrix->capacity = capacity; } void addrow(matrix* matrix, int* row) { if (matrix->rows == matrix->capacity) { matrix->capacity *= 2; matrix->matrix = realloc(matrix->matrix, matrix->capacity * sizeof(int*)); } matrix->matrix[matrix->rows++] = row; }
and in main call function genmatrix , print result out, random values 32691, -1240670624 etc.
int main() { matrix* matrix = genmatrix(); }
when try add row here:
int row[] = {i+j, i*j, i-j}; addrow(matrix, row);
the data adding temporary local variable. on next loop iteration overwritten , when loop exits go out of scope.
you need allocate memory new row data, e.g. using malloc
:
int * row = malloc(3 * sizeof(int)); row[0] = i+j; row[1] = i*j; row[2] = i-j; addrow(matrix, row);
don't forget free
these row allocations later when you're done matrix.
Comments
Post a Comment