Reputation: 35
I'm new to C and I'm trying to define a matrix using a struct and some methods that will change the int** field of the struct. The matrix is supposed to be dynamically allocated and also resizable in how many rows it can have. When I run the program below and print out the values of the matrix in main, the matrix just have random values, not the ones inserted in genMatrix() and addRow(). What am I doing wrong? Very grateful for any help.
I define the struct like this:
typedef struct matrix {
int** matrix;
int rows;
int cols;
int capacity;
} matrix;
And then have the following methods that should change the field of the struct:
matrix* genMatrix() {
matrix* matrix = malloc(sizeof(matrix));
initMatrix(matrix, 100, 3, 200);
for (int i = 0; i < 10; i++) {
for (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*));
for (int i = 0; i < 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 I call the function genMatrix and then print the result out, but get random values like 32691, -1240670624 etc.
int main() {
matrix* matrix = genMatrix();
}
Upvotes: 1
Views: 182
Reputation: 503
row is a local variable.As soon as loop goes for new iteration data gets overwritten and after loop exits data goes out of scope . So use int * row = malloc(NumOfRows * sizeof(int)); and then row members.
Upvotes: 0
Reputation: 212979
WHen you try to add a row here:
int row[] = {i+j, i*j, i-j};
addRow(matrix, row);
the data you are adding is a temporary local variable. On the next loop iteration it will get overwritten and then when the loop exits it will go out of scope.
You need to allocate some memory for the 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 to free
all these row allocations later when you're done with the matrix.
Upvotes: 1
Reputation: 399863
You are storing row
, a local variable. This pointer ceases to be valid once its scope ends:
for (int j = 0; j < 10; j++) {
int row[] = {i+j, i*j, i-j};
addRow(matrix, row);
}
You must dynamically allocate memory for the row data, too.
Upvotes: 0