I have been using Java and quite new to C. I tried to create a function that generates a random pixel array with malloc. I free the memory in another function after using that random array. I think my concept is just fine, but I wonder if I write the codes properly and it really frees the heap memory. It'd be great if you can look at the codes and see if it works.
pixel* randomPalette(int colors){
int i, x;
pixel * randomArr = (pixel *)malloc(sizeof(pixel)* colors);
srand(time(NULL)); //generate a random seed
for (i = 0; i < colors; i++){
x = rand() % 256;
randomArr[i].r = x; randomArr[i].g = x; randomArr[i].b = x;
}
return randomArr;
}
void QuantizeA(pixel* Im, int width, int height){
//create a random palette of 8 RGB colors;
const int num = 8;
pixel* Arr = randomPalette(num);
//find the min distance between pixel and palette color
int x, y, z;
int min = 195075; // max distance is 255^2 + 255^2 + 255^2
int pos = 0;
for (x = 0; x < height; x++){
for (y = 0; y < width; y++){
//compare distance of the pixel to each palette color
for (z = 0; z < num; z++) {
if (distance(Im[pos], Arr[z]) < min){
Im[pos].r = Arr[pos].r;
Im[pos].g = Arr[pos].g;
Im[pos].b = Arr[pos].b;
}
}
pos++; //go to next piexl
}
}
glutPostRedisplay();
free(Arr);
}