Copy data from 2D array to 1D array (5 times bigger)

I am trying copy the data from a 2D array with height*width elements, to a 1D array with 5*height*width elements. Right now, I got this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
float * Netpbm::toArray() {
  float * result = new float(width * height * 5);

  int count = 0;
  for(int i=0; i<height; i++) {
    for(int j=0; j<width; j++) {
      float x = j/width, y=i/height;
      result[count++] = -1 + (2 * x);
      result[count++] = 1 - (2 * y);
      result[count++] = pixels[i][j]->r;
      result[count++] = pixels[i][j]->g;
      result[count++] = pixels[i][j]->b;
    }
  }

  return result;
}


which crashes halfway through the loop with error: SIGSEGV, Segmentation fault. Anyone can give me a hint of how to fix this?

the code above is part of this class:

1
2
3
4
5
6
7
8
9
10
class Netpbm {
protected:
  ...
  int width;
  int height;
  Matrix<pixel> * pixels;
public:
  ...  
  float * toArray();
};


the Matrix template class is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
template <class T>
class Matrix {
private:
    int height;
    int width;
    T ** values;
public:
    Matrix(int height, int width) {
        values = new T*[height];
        for(int i=0; i<height; i++)
            values[i] = new T[width];
        this->height = height;
        this->width = width;
    }

    ~Matrix() {
        for(int i=0; i<height; i++)
            delete[] values[i];
        delete[] values;
    }

    T * operator[](int index) {
        return values[index];
    }
};


does it crash if you set lines 10,11, and 12 to
result[count++] = 42;
??
yes
float * result = new float(width * height * 5);
This allocates one float and direct-initializes it
You wanted
float * result = new float[width * height * 5];
I assume that pixels points to a Matrix<pixel> object, and that pixels->width == width and pixels->height == height.

The following lines are wrong:
1
2
3
result[count++] = pixels[i][j]->r;
result[count++] = pixels[i][j]->g;
result[count++] = pixels[i][j]->b;

Instead they should be:
1
2
3
result[count++] = (*pixels)[i][j].r;
result[count++] = (*pixels)[i][j].g;
result[count++] = (*pixels)[i][j].b;
Last edited on
Still the same error. What I think is happening it's somehow the variable count value is being set after the array limit (5*width*height).

Edit: I just find the error. It was in the declaration, instead of use new float(width * height * 5) I change to new float[width * height * 5] and now the code is working.
Last edited on
Topic archived. No new replies allowed.