return a 2D float array


This is real n00b question, but I am struggling.

After processing an image in a function, I am getting a value as a float, which is a depth for each pixel in a 640x480 image.
How do i return this array of float from this function, or what is the best way to return a 2D array from a function when i have to process it as z value of the image?


You can return a vector instance, which is the best approach if you don’t know how big the array is going to be and don’t want to deal with allocating and deallocating memory.

vector<float> func( ) {  
   vector<float> vf;  
   return vf;  

If you’re just filling an array the best thing to do is to pass a vector to be filled into the method,

void func( vector<float> &vf ) {  
   // fill vf with things  

You also can return a pointer to an array of floats like this:

float* func( ) {  
   float *fp = new float[10];  
   return fp;  

but, and this is a big but, you have to remember to delete that pointer and free its memory later along the line.

…and this can get very messy when returning newly allocated arrays from functions.

float *someArray = func(); // we don't see 'new' so this is tricky  
// .... do something with someArray, and then don't forget:  
delete someArray;  

Objective-c fixed this with autoreleasing objects and now with ARC (Automatic Reference Counting) which releases an object (== deletes the pointer) once nobody is holding on to it anymore. Before ARC, the convention was to return autoreleased objects from methods. If you return a newly allocated (not autoreleased) object from a method, the method’s name should begin with new. I like to stick to this last convention when working with OF. So:

float *someArray = newArray();  // this actually says 'new'  
delete someArray;  // so we don't forget to delete the pointer  

Yeah, I feel weird even pointing that as an option. It’s not “best practice” because it’s just not a very good idea. I guess passing the pointer in is less weird, i.e.

int* create_int(int *p) {  
    p = malloc(sizeof(int));  
    // err checking  
    return p:  
// usage  
p = create_int(p);  


void create_int(int **p) {  
    *p = new int[10];  
    // stuff  
// in main:  

still though: vector. Use the vector. It’s your buddy. And don’t return it, pass it in :slight_smile:

Jup, vector is your friend! Even though I always find the naming a bit weird (like: are we talking STL vectors or ofVec vectors?) they are very convenient because you don’t have to worry about memory at all.


Thanks for the reply. I solved the problem using the vector pointer as discussed.