All pastes #278092 Raw Edit

Something

public text v1 · immutable
·published 2006-12-13 20:58 UTC
rendered paste body
MATRIX* init_matrix (MATRIX* m, int x, int y) {
/*
PURPOSE: Allocate memory for MATRIX m
ACCEPTS: m (MATRIX pointer)
		 x (int) num of rows
		 y (int) num of cols
RETURNS: NULL on error, m otherwise
REMARKS:
*/
	int i; // loop index

	// invalid dimensions
	if (0 >= x || 0 >= y) {
		return NULL;
	}

	free_matrix(m);

	// allocate new array pointers
	m->data = (double**)calloc(x, sizeof(double*));
	if (NULL == m->data) {
		return NULL;
	}

	// allocate data storage
	for (i = 0; i < x; i++) {
		m->data[i] = (double*)calloc(y, sizeof(double));
		if (NULL == m->data[i]) {
			return NULL;
		}
	}

	// assign dimensions
	m->rows = x;
	m->cols = y;

	// allocated successfully
	return m;
}




void free_matrix (MATRIX* m) {
/*
PURPOSE: Frees memory for an allocated MATRIX m
ACCEPTS: m (MATRIX pointer)
RETURNS: (none)
REMARKS: Checks to see if there's anything to free first
*/
	int i; // loop index

	printf("Inside free()\n");
	if (NULL != m->data) {
		printf("m->data is NOT NULL and has %d rows\n", m->rows);
		for (i = 0; i < m->rows; i++) {
			if (NULL != m->data[i]) {
				printf("row %d is not null and will be free()'d\n", i);
				free(m->data[i]);
			}
			else {
				printf("row %d is null\n", i);
			}
		}
		printf("m->data is being freed now\n");
		free(m->data);
	}
	
	m->data = NULL;
}