0

well i had the 2d array but for some reason i need it to be dynamic now so it was like this

const int n=100;  const int m=100;
float matrix1 [n][m];

and i tried to make it like this

int n,m ;
float** matrix1 = new int*[n];
for(int i = 0; i < n; ++i)
    matrix1[i] = new int[m];

i need all the elements inside the array to be floats

  • 1
    instead of `new int*[n]` use `new float*[n]`, and instead of `new int[m]` use `new float[m]` – Chris Rollins Apr 30 '19 at 00:26
  • @ChrisRollins can i initialize this array under the including area out side all the functions ? – Yusuf Sameh Apr 30 '19 at 00:30
  • 1
    it is possible to declare the pointer globally but you can't run a for loop in the global scope, so you'd have to have the initialization occur in a function. – Chris Rollins Apr 30 '19 at 00:33
  • ohh thank you. its like 3 hours i've been trying to write a for loop globally – Yusuf Sameh Apr 30 '19 at 00:35
  • @YusufSameh [Please see this answer](https://stackoverflow.com/questions/21943621/how-to-create-a-contiguous-2d-array-in-c/21944048#21944048). Your method of creating the array is one of the worst ways of doing this. – PaulMcKenzie Apr 30 '19 at 02:12

1 Answers1

3

Avoid this approach, it'll trash your cache access. Use a 1d array, and create a function that can access elements via 2 indices.

Otherwise, std::vector is safer to use than a raw pointer and comes with almost no performance penalties in release builds.

Like:

unsigned int n = 100;
unsigned int m = 1000;

std::vector<float> data(n * m, 0.0f);

auto accessor = [&](unsigned int x, unsigned int y) -> float& {
    // optional bounds checks here
    return data[x + y * n];
};

// Do something with your data.
accessor(1, 2) = 1.0f;

A better approach would be to wrap it up in a struct/class that also stores dimensions.

Pál Mezei
  • 31
  • 2