0

What is the best way to display a 2D matrix using CImg? I am trying the following code but it is giving me a segmentation fault:

    float matrix[100][100];
    int i;
    int j;

    for (i=0; i<100; i++) {
        for (j=0; j<100; j++) {
            matrix[i][j] = 10.0*sin((float)j/(2.0*3.1416));
        }
    }

    CImg<float> img(100,100,1,1);

    img._data = &matrix[0][0];
    img.display("Test");

What am I doing wrong?

Jaime Ivan Cervantes
  • 3,579
  • 1
  • 40
  • 38

1 Answers1

1

What you did is probably not a good idea : The destructor ~CImg<T> will try to dealloc the buffer associated to your CImg<T>instance, and as you have forced its value to be matrix, you will get into big troubles. I suggest to use shared images instead, it is efficient (no additional memory copy) and safe to use :

CImg<float> img(matrix,width,height,1,1,true);  // img is a 'shared' image.
img.display("Test");
bvalabas
  • 301
  • 1
  • 1
  • Shared image was exactly what I was looking for, but when I use your code I get an error that says `instantiated from cimg_library::CImg::CImg(const t*, unsigned int, unsigned int, unsigned int, unsigned int, bool) [with t = float [100], T = float]` – Jaime Ivan Cervantes Apr 24 '14 at 15:06
  • I solved it using `CImg img((const float*)matrix,width,height,1,1,true)` – Jaime Ivan Cervantes Apr 24 '14 at 15:21