Ok i have this:
Code:
void array_dump();
void print_array();
void free_color_array();
int width = 256;
int height = 256;
struct RGB
{
unsigned char red;
unsigned char green;
unsigned char blue;
};
struct RGB **color_array;
main()
{
array_dump();
print_array();
free_color_array();
}
void print_array()
{
int i;
int j;
for(i = 0; i < height; i++)
{
for(j = 0; j < width; j++)
{
printf("(%d ", (unsigned char)color_array[i][j].blue);
printf("%d ", (unsigned char)color_array[i][j].green);
printf("%d) ", (unsigned char)color_array[i][j].red);
}
printf("\n");
}
}
void array_dump()
{
int i;
int j;
color_array = (struct RGB**)malloc(sizeof(unsigned char)*3*height);
for(i = 0; i < height; i++)
{
color_array[i] = (struct RGB*)malloc(sizeof(unsigned char)*3*width);
}
for(i = 0; i < height; i++)
{
for(j = 0; j < width; j++)
{
color_array[i][j].blue = (unsigned char)20;
color_array[i][j].green = (unsigned char)20;
color_array[i][j].red = (unsigned char)20;
}
}
}
void free_color_array()
{
int i;
int j;
for(i = 0; i < height; i++)
{
free(color_array[i]);
}
free(color_array);
}
Very simple right.
The problem is that it seg-falts, but the real problem is where i found it seg-falting
if i change my array_dump() function to this:
Code:
void array_dump()
{
int i;
int j;
color_array = (struct RGB**)malloc(sizeof(unsigned char)*3*height);
for(i = 0; i < height; i++)
{
color_array[i] = (struct RGB*)malloc(sizeof(unsigned char)*3*width);
}
}
*Notice that it is the exact same code but the two bottom for loops are cut out, so i am just allocating the array and not setting the values
This will run fine and print out the system junk gathered durning allocation when print_array() is called.
If you will also Notice that the two for loops that where cut out of array_dump() are the exact same in structure to the ones in print_array(), the only difference is the what is happening inside the for loops.
So i tell my self, maybe my color_array is not being allocated correctly, which could in turn allow my print_array() function to be wayward and just look at any thing it likes to. So i add one to width and height before i enter the for loops in print_array() and low in behold it prints all the way to the end and then seg-falt. This should mean that my malloc code in array_dump is working correctly. SO WHY ARE THE LAST FOR LOOPS IN array_dump SEG-FALTING?
Thanks for any help