Re: allocate a 2d array of floats?
Re: allocate a 2d array of floats?
- Subject: Re: allocate a 2d array of floats?
- From: Alastair Houghton <email@hidden>
- Date: Fri, 21 Nov 2003 11:47:14 +0000
On 21 Nov 2003, at 06:36, Jay Rimalrick wrote:
>
What is the best way to allocate a 2d array of floats in objective c?
>
I would
>
assume that you would just do it the same way as in c but I am not
>
sure how
>
to. Also how would you deallocate the memory?
There are two approaches in common use, namely:
float *array = (float *) malloc (sizeof (float) * array_width *
array_height);
/* Then array[x + y * array_width] is the element at (x, y)... when
I'm using
this approach, I often define a macro, as follows: */
#define ARRAY(x,y) array[(x) + (y) * array_width]
/* Now use the array */
...
/* And release it */
free (array);
and
float **array = (float **) malloc (sizeof (float *) * array_height);
float *data = (float *) malloc (sizeof (float) * array_width *
array_height);
unsigned n;
for (n = 0; n < array_height; ++n)
array[n] = data + n * array_width;
/* Now you can access the elements in the array using array[y][x]. */
/* Use the array */
...
/* And release it */
free (data);
free (array);
Sometimes people do a daft version of the latter, where they call
malloc() array_height times. On PPC, I would expect the first version
to outperform the second one in almost all cases. The latter technique
does, of course, have some advantages if you need to rearrange the rows
of the array (e.g. for linear programming).
(It *is* possible to combine the two malloc() calls in the latter
example into a single call... however, if you do so, you are making
assumptions about the alignment requirements of a "float".)
The other thing to note is that, for some types of scientific codes,
other arrangements are used (for example, triangular arrays).
Kind regards,
Alastair.
[demime 0.98b removed an attachment of type application/pkcs7-signature which had a name of smime.p7s]
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.