I'm supposed to create a c file that contains functions perform certain tasks with a structured matrix. My h file and current c file are as follows.

typedef struct 
	{
		int rows, cols; //matrix dimensions
		int **elements; //element array
	}	Matrix;

	void matrixInit (Matrix* m, int r, int c); //Initializes m with values r row and c column
	void matrixCopy (Matrix* m, Matrix* n); //Stores an exact copy of matrix n in matrix m

	int matrixGetElement (Matrix* , int r, int c); //Return the value of the element in the r row and c column
	int matrixGetRows (Matrix*); //Returns the value stored in rows
	int matrixGetCols (Matrix*); //Returns the value stroed in columns

	void matrixSetElement (Matrix*, int r, int c, int v); //Stores the value (v) in the matrix at location r, c

	Matrix* matrixAdd (Matrix*, Matrix*); //Return the sum of two matrices
	Matrix* matrixSubtract (Matrix*, Matrix*); //Return the difference of two matrices
	Matrix* matrixMultiply (Matrix*, Matrix*); //Return the product of two matrices

	void matrixDestruct (Matrix* m); //Frees the memory allocated with matrix m

and my c file...

#include <stdio.h>
#include <stdlib.h>
#include "matrix.h"


void matrixInit (Matrix* m, int r, int c)
{
	int i, k;
	m->elements = (int**) malloc( sizeof( int* ) * (r) );
		for (i = 0 ; i <= r ; i++)
		{
			m->elements[i] = (int*) malloc (sizeof (int) * (c) );
			for (k = 0 ; k <= c ; k++)
			{
				m->elements[i][k] = 0;
			}
		}
}

void matrixCopy (Matrix* m, Matrix* n)
{
	int a, b;
	for (a = 0 ; a < m->rows ; a++)
	{
		for (b = 0 ; b < m->cols ; b++)
		{
			m->elements[a][b] = n->elements[a][b];
		}

	}
}

int matrixGetElement (Matrix*, int r, int c)
{
	
}


int matrixGetRows (Matrix*)
{
	
}

int matrixGetCols (Matrix*)
{
	
}

void matrixSetElement (Matrix* m, int r, int c, int v)
{
	int i, k;
	m->elements = (int**) malloc( sizeof( int* ) * (r) );
		for (i = 0 ; i <= r ; i++)
		{
			m->elements[i] = (int*) malloc (sizeof (int) * (c) );
			for (k = 0 ; k <= c ; k++)
			{
				m->elements[i][k] = v;
			}
		}
}

I'm just unsure how to return the values from the structure with designating a matrix like this:

int matrixGetElement (Matrix* m, int r, int c) //that is without having the "m"
{
	
}

>>for (k = 0 ; k <= c ; k++)

Should be < c, not <= c.

>>I'm just unsure how to return the values from the structure with designating a matrix like this
The same as you would any other matrix return m->elements[r][c];

>>I'm just unsure how to return the values from the structure with designating a matrix like this:

int matrixGetElement (Matrix* m, int r, int c) //that is without having the "m"
{
	
}

Sorry! could'nt get the problem.

Edited 6 Years Ago by vinitmittal2008: n/a

This article has been dead for over six months. Start a new discussion instead.