I'm trying to return the size of a matrix (i.e. something which has the form [A.height, A.width], so it's an array) from a function but C++ won't let me.
I gather that you can't simply return arrays and that pointers must be used. Could anybody show me the easiest way to do this? Here's my function
1 2 3 4 5 6 7 8 9 10
int size(matrixdouble_new &A)
{
// We define an array to contain [height(A), width(A)], i.e. the size of A
int size_A [2];
size_A[0] = A.height;
size_A[1] = A.width;
return size_A;
}
- Returning a pointer pointing to a local object is hazardous.
- I think of creating size_A on the heap then return the pointer pointing to size_A[0], but allocating memory in one function while freeing it in another can be dangerous.
- On line 3 it looks like in the "pointer version" of this you are going to assign a pointer to another, but if you call delete on one later on, you would create a stray pointer...
- You may create the pointer in the calling function, then pass the pointer to the function (similar to what melkiy did), but you have to also pass in the pointer...
You are trying to do something that doesn't make much sense in C++. It is better if you make yourself a matrix class, which will provide you with information about its size, etc.
Can you be more specific about the matrixdouble_new type?
[edit] Argh. I just found your other thread (which I don't want to read). Your matrix class should be able to report its size. Here is an example to get you started: