Declaring an array inside function

hello, I have recently tried to create a function that sums two different arrays. For this, inside the function, I need to declare a double pointer (double **pout), but what if I am using the "new" command? As far as I know, every time you declare something with "new", you need to use "delete" at the end in order to erase that from the memory. My question is: If I'm declaring the variable as in the code below, do I need to use "delete" inside the function? I am just afraid that, for bigger matrices values, the memory can be "eaten" if this is not done, Thanks!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 
double **sum(double **A, double **B, int dim){
	
	double **pout=new double*[dim];
	for(int i=0;i<dim;i++){
		pout[i]=new double[dim];
		
	}
	
	for(int i=0;i<dim;i++){
		for(int j=0;j<dim;j++){
			
			pout[i][j]=A[i][j] + B[i][j];			
		}		
	}	
	return pout;
}
Consider using std::vector<> or if the program has a lot of mathematical operations on arrays std::valarray

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <valarray>
#include <iostream>

int main()
{
    // http://en.cppreference.com/w/cpp/numeric/valarray
    const std::valarray<double> a { 1.2, 3.4, 5.6, 7.8, 9.0 } ;
    const std::valarray<double> b { 12.1, 34.3, 56.5, 78.7, 90.9 } ;

    const std::valarray<double> c = a+b ;
    for( std::size_t i = 0; i < c.size(); ++i ) std::cout << c[i] << ' ' ;
    std::cout << '\n' ;

    const std::valarray<double> d = a*b ;
    for( std::size_t i = 0; i < d.size(); ++i ) std::cout << d[i] << ' ' ;
    std::cout << '\n' ;

    const std::valarray<double> e = std::sqrt( d / 10.0 ) ;
    for( std::size_t i = 0; i < e.size(); ++i ) std::cout << e[i] << ' ' ;
    std::cout << '\n' ;
}

http://coliru.stacked-crooked.com/a/37d43f66bf3e1fc0
@ JLBorges The solution you provide is for uni-dimensional arrays? Would does this also work for multi-dimensional?

If your multi-dimensional array is too big you could get a segmentation fault problem according with what I read here:
https://stackoverflow.com/questions/1847789/segmentation-fault-on-large-array-sizes

They suggest also to use multi-dimensional vector instead of multi-dimensional arrays. Here are a thread on how to:
http://www.cplusplus.com/forum/general/833/

For your question:
do I need to use "delete" inside the function?

Yes you need a delete inside the function if you want to free the dynamic memory allocation.

Hope it helps.
Last edited on
if you do find yourself in this situation, there are a number of ways to handle it.
1) old school, you simply document where the delete needs to happen. It is acceptable for the caller of a function to destroy the memory returned by the function, but this is not as common a practice as it was back when.

2) you can make a mini class or struct that destroys the memory for the object when it goes out of scope, and use the object instead of pointers as the types.

3) you can use one of the various smart pointer objects out there. Many of these are bloated, though.

4) here, as already said, you can use the c++ containers above instead of a pointer. This is the best way for your specific code. Options 2 and 3 may come up in other designs though. Option 1 you should understand in case you encounter it in legacy code.

> The solution you provide is for uni-dimensional arrays?
> Would does this also work for multi-dimensional?

A multi-dimensional array can be simulated with the help of std::slice
http://en.cppreference.com/w/cpp/numeric/valarray/slice
you can also reshape the pointers but if you mess it up you have memory errors (like any other mangled pointer code, but this one is more prone to it if the coder does not understand it very well). I prefer the other direction, allocate single d and access as if 2-d with an inline accessor function. Are you able to use the containers, or confined to a pointer solution?

Matrix math specifically is a mess with 2-d pointer approach. For bigger matrices you can have page fault problems, and for a large # of common operations you end up having to copy and allocate the data structures excessively to do things like transpose, append X for RREF solve, multiplication, factorization, and more.
Last edited on
@zaratustra,

It may be that the appropriate solution for you depends on what you intend to do with your matrices. Once you start talking about "big" matrices an alarm bell starts ringing about sparse matrices, in which you only store the non-zero elements: often just 3, 5 or 7 non-zero bands for many physical problems, for example.

It's a personal preference but I rarely use multidimensional arrays directly, but, as @jonnin advises, use a 1-d array and access with conversion functions (n=MAXJ*i+j and its inverse) in places where it is needed. Adding 1-d arrays is, after all, rather easy.

I also concur with @jlborges about the use of valarray: it's nice (and I'm told it's efficient) to be able to write c = a + b to sum two entire arrays (with many more array-based mathematical functions as well). It's also how all arrays work in modern fortran.

So maybe we can request that you say what type of matrix you are working with and the intended use.
Thanks for the replies guys, I think I managed to overcome the confussion by just defining another argument in the function declaration, which is the result pointer. Then the pointer that is about to be converted can be declared inside the "main" function, therefore all "delete" happens at the end of the code, and no dynamical memory is left occupied. My next step is to build up a "matrix" class to englobe all possible matrix operations over matrix objects, but I am just starting to play with this :D !!

Topic archived. No new replies allowed.