CFD Online Discussion Forums

CFD Online Discussion Forums (https://www.cfd-online.com/Forums/)
-   Main CFD Forum (https://www.cfd-online.com/Forums/main/)
-   -   dynamically allocated memory in C++ (https://www.cfd-online.com/Forums/main/12498-dynamically-allocated-memory-c.html)

Junseok Kim November 1, 2006 19:53

dynamically allocated memory in C++
 
I want to convert C program into C++ frame work. Would you help me out the following problem.

I want to use new and delete for the following routinues. Thank you in advance.

If possible, I need a full sample program using the following routines.

double **dmatrix(long nrl, long nrh, long ncl, long nch) {

double **m;

long i, nrow=nrh-nrl+1+NR_END, ncol=nch-ncl+1+NR_END;

m=(double **) malloc((nrow)*sizeof(double*));

m+=NR_END;

m-=nrl;

m[nrl]=(double *) malloc((nrow*ncol)*sizeof(double));

m[nrl]+=NR_END;

m[nrl]-=ncl;

for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;

return m; } void free_dmatrix(double **m, long nrl, long nrh, long ncl, long nch) {

free(m[nrl]+ncl-NR_END);

free(m+nrl-NR_END);

return; }

Márcio November 3, 2006 05:55

Re: dynamically allocated memory in C++
 
the changes in your code would be in the allocation / dealocattion commands. The access to the elements in the matrix would be in the same way.

double **m; //unchanged

m = new double*[nrow];

instead of m=(double **) malloc((nrow)*sizeof(double*)), each row would be allocated simmilarly to this:

for(size_t i=0;i < nrow;++i) m[i] = new double[nrow*ncol];

and, to deallocate,

for(size_t i=0;i < nrow;++i) delete[] m[i];

delete[] m;

but, instead of doing this, you should consider using the STL containers, like std::vector or std::valarray, which is best suited for scientific computing.

tip: There's a lot of C++ material on the net, like the book "Thinking in C++", for example, or an online guide on the site www.informit.com, and tons of material in other sites. It's realy worth spending some time searching for it.

I Hope it helps

-Márcio


chris November 3, 2006 06:24

Re: dynamically allocated memory in C++
 
I bet you meant

for(size_t i=0;i < nrow;++i) m[i] = new double[ncol * sizeof(double)];

instead of

for(size_t i=0;i < nrow;++i) m[i] = new double[nrow*ncol];

;-).

Márcio November 3, 2006 09:19

Re: dynamically allocated memory in C++
 
oops! Thank you.

O. November 6, 2006 03:15

Re: dynamically allocated memory in C++
 
For the records: new double[100]; will allocate 100*sizeof(double) bytes in memory (800 bytes on most machines). new double[100*sizeof(double)]; will allocate 100*sizeof(double)*sizeof(double) bytes in memory (6400 bytes on most machines). !!!!


Angen November 13, 2006 14:22

Re: dynamically allocated memory in C++
 
Good point O.

Angen



All times are GMT -4. The time now is 21:14.