Knol

I’ve decided that I’m going to shift my efforts at TODO articles to knol for two reasons:

1.) It allows me to post to my site (through links) while being able to deliver information  to more people (due to certain bandwidth constraints).

2.) I can get some real feedback from interested people

I’ll still posts small stuff here but my longer walkthroughs and stuff will be going up on Knol and hopefully getting some more attention.

Lot’s Of Work

I just finished a tremendously long weekend and sadly have to make my schedule for the coming week which is finals. I will likely be making a post sometime around there, sorry for the delay, haven’t had time or ideas to post anything useful.

Nothing New

Nothing really new has come up and I’ve been insanely busy but I should be making an interesting update within two weeks and adding a page for the chess program I’m developing.

Allocating Space for 2d Arrays with malloc()

Yet another post in my effort to be helpful. If you want to allocate space for a two dimensional array you need to be careful. Remember that a 2d array of floats is a float**, meaning a pointer to a block in memory which is a list of float pointers. Each of these float pointers is a pointer to an array of floats. If you want a couple functions to do this for you, you are in luck:

void allocate_matrix(float*** A, int n, int m) {
	int i;
	// Allocate storage for pointer array
	*A = malloc(n * sizeof(float *));
	if (A == NULL) {
		printf("Error: malloc could not allocate %d bytes for a\n", n
				* sizeof(float *));
		return;
	}

	for (i = 0; i < n; i++) {

	(*A)[i] = malloc(n * sizeof(float));
	if ((*A)[i] == NULL) {
		printf("Error: malloc could not allocate %d bytes for a\n", n
				* sizeof(float));
		return;
	}

	}
}

void free_matrix(float*** A, int n) {
	int i;
	for (i = 0; i < n; i++)
		free((*A)[i]);

	free(*A);
}

Remember that we need to take in a float*** because when we call the function we need to do this:

float** A;
allocate_matrix(&A, n, m);

Otherwise our pointer is copied and lost due to out of scope. Don’t forget that you need to free your 2d array the same way. This method is useful because gcc and many compilers have a limit on how much space you can just statically allocate. I found I can’t get much bigger than a 1500×1500 array without seg faulting at runtime. You might be able to increase the maximum size but the ideal way is to allocate the memory yourself.

 

Hope this way useful.