0

I have a function:

void foo(double[][4]);

which takes a 2d array with 2nd dimension equal to 4. How do I allocate a 2d array so that I can pass it to the function? If I do this:

double * arr[4];
arr = new double[n][4];

where n is not known to the compiler. I cannot get it to compile. If I use a generic 2d dynamic array, the function foo will not take it.

6
  • 1
    why you don't you a std::vector? array is just c not c++ Commented Sep 22, 2016 at 11:52
  • @Android400 vector is not alternative to old style array.. std::array is Commented Sep 22, 2016 at 11:52
  • When in doubt, use a vector. Solves all the headaches of dealing with arrays directly. Commented Sep 22, 2016 at 11:52
  • @HumamHelfawi I know but the size isn't static. So a vector could be also a possilbe solution whitout a big overkill. Commented Sep 22, 2016 at 11:58
  • @Android400 yes in that case. but since The OP has a function that needs array I saw the vector as not an option. Commented Sep 22, 2016 at 12:04

4 Answers 4

4

As asked, it is probably best to use a typedef

 typedef double four[4];
 four *arr;     // equivalently double (*arr)[4];
 arr = new four[n];

Without the typedef you get to be more cryptic

double (*arr)[4];
arr = new double [n][4];

You should really consider using standard containers (std::vector, etc) or containers of containers though.

Sign up to request clarification or add additional context in comments.

Comments

2
 typedef double v4[4];
 v4* arr = new v4[n];

Consider switching to arrays and vectors though.

Comments

0

I know it may not be what OP has intended to do, but it may help others that need a similar answer.

You are trying to make a dynamic array of statically success array. The STL got your solution: std::vector and std::array

With these containers, things are easy easier:

std::vector<std::array<int, 4>> foo;

// Allocate memory
foo.reserve(8);

// Or instead of 8, you can use some runtime value
foo.reserve(someSize);

// Or did not allocated 8 + someSize, but ensured
// that vector has allocated at least someSize

// Add entries
foo.push_back({1, 2, 3, 4});

// Looping
for (auto&& arr : foo) {
    arr[3] = 3;
}

// Access elements
foo[5][2] = 2;

Comments

-2

Alternatively to creating a new type and occupying a symbol, you can create a pointer to pointer, and do it like that:

double **arr = new double*[j];
for (int i = 0; i < j; ++i)
{
    arr[i] = new double[4];
}

whereas j is the int variable that holds the dynamic value. I've written a simple code that shows it working, check it out here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.