Re: Multidimensional array member initialization
<olivier.scalbert@algosyn.com> ha scritto nel messaggio
news:c5deac91-7a8b-48f0-bf6c-80faaa34c096@j24g2000yqa.googlegroups.com...
Hello,
As you can imagine, I have some problems around the pixels definition.
I see two alternatives:
- using templates;
- allocate a single dimension array of pixels and manage the
coordinates conversion myself.
i don't know
here is my solution (don't know if it is right)
------------------------
#include <iostream>
#include <stdlib.h>
using namespace std;
struct Color3d{
float r, g, b;
};
class Image{
public:
Image(int width, int height);
~Image();
void fill(Color3d& color);
int width;
int height;
Color3d** pxs;
};
Image::Image(int w, int h)
{int i, g, gg;
width=0; height=0; pxs=0;
if(w<=0||h<=0) return;
g =h*sizeof(Color3d*);
if(g<=0) return;
gg=w*sizeof(Color3d); // pixel are h*w
if(gg<=0) return;
pxs=(Color3d**) malloc(g);
if(pxs==0) return;
for(i=0; i<h; ++i)
{pxs[i]=(Color3d*) malloc(gg);
if(pxs[i]==0)
{for(--i; i>=0; --i)
free(pxs[i]);
free(pxs); pxs=0;
return;
}
}
width=w; height=h;
}
Image::~Image()
{int i;
if(pxs==0) return;
for(i=0; i<height; ++i)
free(pxs[i]);
free(pxs);
}
void Image::fill(Color3d& color)
{int x, y;
if(pxs==0) return;
for(x=0; x<height; ++x)
{for(y=0; y<width; ++y)
pxs[x][y]=color;
}
}
int main(void)
{Color3d h={0.78373, 0.1383, 1-0.78373-0.1383};
Image g(1024, 768);
if(g.pxs==0)
{cout << "Error\n"; return 0;}
g.fill(h);
cout << "(r,g,b)==(" << g.pxs[0][0].r << ", "
<< g.pxs[0][0].g << ", "
<< g.pxs[0][0].b << ")\n";
return 0;
}
I am sure there are some more elegant solutions, but I have no ideas.
Thanks to help me,
Olivier