[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[netCDF #GMX-529879]: Using C++ dynamic memory allocation



Hi Rafael,

> I am trying to Store/Write an "NcVar" variable into a  2-dim Array using
> C++ dynamic memory allocation (double pointer) and the NcVar does not
> copy/write itself properly into my C++ array. However if instead of
> using dynamic memory allocation, that is to say if I use a constant
> dimension double array it works fine.
> 
> The only problem is that I don't know before hand how the size of my
> array, since it's problem dependent and if I assign too much memory to
> my constant dimension double array I run into compilation problems and
> memory mis usage.
> 
> Do you know any ideas that I could try to bypass this problem?

Yes, you must make sure the memory you have allocated for the data 
requested in each read is a single, contiguous block of memory.
That is required because the C++ API calls into the C library to do
the I/O, and the C library (except for the nc_get_varm_TYPE calls, 
which are not available from the C++ API) requires contiguous space 
into which data will be read for each call.

So you can still allocate memory dynamically of the right size for
your 2D array, but you must make sure the allocation is contiguous,
as if you were just allocating a 1-dimensional array.  It is
possible with C++ operator overloading to make the result appear as
if it is a 2-dimensional array, however it may be easier just to use
arithmetic on the indexes.  

For example, if you have an M by N array that you want to read,
allocate M*N contiguous elements in a 1-dimensional array.  To access 
the [i][j] element of the 2-dim array (zero-based), you would access 
the kth element of the 1-dim array, where k is (j + N*i).

--Russ


Russ Rew                                         UCAR Unidata Program
address@hidden                     http://www.unidata.ucar.edu



Ticket Details
===================
Ticket ID: GMX-529879
Department: Support netCDF
Priority: Normal
Status: Closed