10-05-2001 11:57 AM
A. Clay Stephenson gave me an example of how to allocate a variable sized array in C but his example was for a one-dimensional array. Is this also possible with two-dimensional arrays?
I like to understand the big picture before I start on a project this big.
Thanks in advance.
Solved! Go to Solution.
10-05-2001 01:06 PM
I spent about 5 minutes putting together the 2 dimensional version. In fact, this technique can be extended to n dimensions. The problem is that this gets pretty deep pretty quickly.
In this case I set up an array of records, arry2;
The key is that arry2 is declared as my_rec **arry2 but USED in an array context. What you do is first allocate the rows and then allocate the columns associated with each row.
We still haven't covered the case of truly dynamic arrays. In this case, the arrays are set up but do not change beyond that. It allows you to size arrays from the command line or from a configuration file but does not allow you to expand them as needed. That too is possible but I'm already beginning to feel that I am teaching C again.
Anyway, here's the attached code.
10-05-2001 03:58 PM
I confess I did cheat a little bit. I basically yanked that out of some existing code and added the part dealing with looping through the array. Since you mentioned dynamic arrays, I've been racking my brain trying to remember how I used to do that in Pascal. I remember something about using a free union and turning range checking off around any code that accessed the array by I can't remember much beyond that.
10-08-2001 07:08 AM
Thank you for your two-dimensional array example. I can't seem to do the allocation in a function. I have about ten arrays of the same record type but withing different size. I know this is something simple but these ******** C pointers are insane. Can you show me how to do this?
10-08-2001 07:37 AM
Can I show you how to do this? Does a hog like slop?
Actually C pointers are not insane, it's just that in Pascal you have pass by value and pass by reference (VAR) so that the underlying details were hidden. In Pascal, you could go all the way through a first semester course and never see a pointer; in C you might go to or two days.
The key here is *** my_rec - a pointer to a pointer to a pointer. I've modified the earlier code to include a integer function allocate_array. 0 means all went well. You specify the number of rows and columns and the *** my_rec. I've commented the call so you see to use the & operator in the function call. This is similar to a boolean function in Pascal with one of the VAR params being set as a side effect. The other method is to let the function return the array itself or NULL on failure. I'll do that variant if I have time.
10-08-2001 08:24 AM
Here is the other method that returns a pointer to the array. I really prefer the previous method since the status is returned as well as a pointer. The code is a bit clearer in this example.