Intel's Ronler Acres Plant

Silicon Forest
If the type is too small, Ctrl+ is your friend

Tuesday, July 7, 2009

Dyanmic Two Dimensional Arrays in C

In computer programming, a list of numbers can be stored in an array. The size of the array can be decided in advance when you write the program, or you can create the array at run time to be any size you want. A simple list is called a one dimensional array.

A two dimensional array is more like a spreadsheet. You have rows and columns. The C programming language supports two dimensional arrays that are created when you write the program, but it does not support dynamic creation of two dimensional arrays.

However, a two dimensional array can be viewed as a list of lists, and because C treats pointers and arrays pretty much interchangeably, it is possible to dynamically create a data structure that functions as a two dimensional array. The computation of the actual address in memory of the data field being accessed may not be as elegant as that done for static two dimensional arrays, but it may be faster as it only involves addition and no multiplication. There is some overhead in storage for an extra row of pointers, but that should not be a problem for today's computers.

I did this once before, but the code wandered off. I am playing with matrices these days, so I decided to redo it. It is not particularly complicated, but you do need to get the details right to make it work. I put the essentials in a demo program you can examine should you be so inclined.

No comments: