Jack Farrow
Jack Farrow

Reputation: 817

C++ Optimal way of returning multidimensional array from function, pointers?

I need to return an array of class objects from a function. I understand from research that the best way to do this is with a pointer, but is this the best way given my program design, and the need to access this from multiple CPP files?

main.cpp

#include <class.h>
#include <functions.h>

int main(){
Class Object[2][]; //define second dimension here?
some_function(); //should return / create the array with filled in elements.
int var = arr[2][3]; // want to be able to do something like this in main
}

functions.cpp

void some_function(){
// assign values
arr[2][3] = 1;
}

Upvotes: 1

Views: 522

Answers (1)

Tony The Lion
Tony The Lion

Reputation: 63190

You should really use std::vector<std::vector<Object> > for your multi-dimensional array. Using raw arrays is error prone, and since you're using C++ anyways, why not make use of something as useful as the std::vector which automatically resizes when needed.

You can even return the vector from your function like so:

std::vector<std::vector<Object> > my_function() { /* do something */ return some_vector; }

Upvotes: 8

Related Questions