Nevermind running out of time and cant find it for the life of me, I'll just have mods clean this up when I am done:
We are just working with a 2D matrix loaded into a 1D array, between the pointers and structures I am lost.
Program compiles but regardless of how many changes I make, I faced with: segmentation fault (core dumped).
Code
#include<stdio.h>
#include<stdlib.h>
int i,j;
/* create type called matrix_t that holds dimensions and pointer*/
typedef struct matrix{
int rows; /* number of rows*/
int cols; /* number of columns*/
int *datalocation; /* pointer to where data is stored*/
} matrix_t;
/*create a new matrix and allocate memory */
matrix_t * new_matrix(int rows, int cols) {
matrix_t * onedimensionalmatrix = (matrix_t *) malloc(rows*cols);
/*set row and column size for manipulation*/
onedimensionalmatrix->rows = rows;
onedimensionalmatrix->cols = cols;
/* set all values of matrix to zero by default */
for(i = 0; i < (rows*cols); i++){
onedimensionalmatrix->datalocation[i] = 0;
}
return onedimensionalmatrix;
}
/* neatly print the matrix */
void print_matrix(const matrix_t * matrix){
for (i = 0; i < (matrix->rows); i++)
{
for (j = 0; j < (matrix->cols); j++)
{
printf("%d \t",matrix->datalocation[i*j]);
}
printf("\n");/* skip line */
}
}
int main(){
matrix_t * tester;
tester = new_matrix(10,10);
print_matrix(tester);
return 0;
}
My instructors advice: Quote
I didn't run your code, but it looks reasonable. The reason you are getting the seg fault (or at least part of it) is this line:
matrix->datalocation[i*j]
in print matrix. You need to convert the row/col coordinates (in this case, i & j) to the index in datalocation. There is a post on the discussion board about how to do that. Other than that it looks good. just make sure you have this much working before you move on - with a good base the rest of it is much easier.
I couldnt find a related discussion post and I have made multiple manipulations.
ALSO the method values and parameters are set in stone.
Is there an issue with me using typedef instead of constant when defining matrix_t?as it stands, it compiles with no errors, and I cannot continue my project until this portion is complete.
Feel free to rip me apart here.
Thanks!