Memory Allocation Problem
Brian K. W. Hook
jdb at reef.cis.ufl.edu
Thu Jan 24 01:04:33 AEST 1991
In article <7156 at crash.cts.com> kevin at crash.cts.com (Kevin Hill) writes:
>
> I am still having problems with the malloc use in allocating memory
>for a two dimensional array. I thank everyone that has been attempting
>to help me with this.
I don't know exactly what system you are writing on, but I assume that it
is PC compatible. Actually, some code looks like Mac, but either way it
is not very relevant.
Have you tried using a SINGLE pointer instead of two? Or are you doing
something that I am not aware of. For example, I wrote a windowing
library that looks much like some of that code you are using (which actually
looks quite a lot like the MetaWINDOWS library).
typedef struct _window {
int width, height;
BYTE *oldImage;
...
} WINDOW;
While it is more intuitive to declare an array of pointers for a rectangular
region I have found that the following works REAL well and adds some
simplicity.
void createWin ( WINDOW *wnd /* Whatever else needs to be passed */ )
{
...
wnd->oldImage=(BYTE *)(malloc(wnd->width*wnd->height)+1); // I add 1
// just in case
...
}
This assumes that the WINDOW doesn't cast a shadow and that the area behind is
definable as a BYTE (8 bits, as far as I am concerned...a 256 color bit map)
for each discreate location behind the WINDOW (i.e. pixel).
Now, back to the two dimensional array. How about indicing each pointer
that you need using a little bit of pointer arithmetic. The equation
should be:
BYTE *rowToFind=wnd->oldImage+(wnd->width*row+column);
This assumes that "row" and "column" is the starting pixel for the address you
wish to find. Since you are looking for a pointer per row (thus simulating
a two dimensional array) "column" would be 0. Then you would just grab
wnd->width amount of BYTEs to get that entire line.
Hope this helped,
Brian
More information about the Comp.lang.c
mailing list