I have a piece of code that stores bytes from an image into a multidimensional array stored in a struct. While assigning the bytes to the array both the expected data (0xFF since I am testing with a pure white image) and the data that is actually pointed to by the array at pixel_array[i][j][k] match. Here is a snippet of the code that stores data in the array:
unsigned char pixel[bmp_image->pixel_width];
bmp_image->pixel_array = malloc(bmp_image->width * sizeof(unsigned char));
for (int i = 0; i < bmp_image->width; i++) {
bmp_image->pixel_array[i] = malloc(bmp_image->height * sizeof(unsigned char));
for (int j = 0; j < bmp_image->height; j++) {
bmp_image->pixel_array[i][j] = malloc(bmp_image->pixel_width * sizeof(unsigned char));
fread(pixel, sizeof(pixel), 1, bmp_data);
// Pixel width refers to the size of a pixel in bytes
for (int k = 0; k < bmp_image->pixel_width; k++) {
bmp_image->pixel_array[i][j][k] = pixel[k];
// These two print statements always result in the same data (i.e. both print 0xFF for the white test image)
printf("Expected byte: %x\n", pixel[k]);
printf("Saved byte: %x\n\n", bmp_image->pixel_array[i][j][k]);
}
}
fseek(bmp_data, padding, SEEK_CUR);
}
And here is the struct storing image data:
struct Image {
FILE *image_file;
int width;
int height;
int pixel_width;
int error_code;
unsigned char*** pixel_array;
};
My issue is that as soon as I try to access chars stored in the pixel array using the following code I get random unexpected output (i.e. not hex FF)
for (int i = 0; i < bmp_image->width; i++) {
for (int j = 0; j < bmp_image->height; j++) {
for (int k = 0; k < bmp_image->pixel_width; k++) {
printf("%x", bmp_image->pixel_array[i][j][k]);
}
}
}
An example of the output with a 10x10 white image can be seen below (expected to be only ff):
6050a3c051a32053a38054a3e055a34057a3ffffffffffffffffffffffffc04ca3404da3fffffffffffffffffffffffff
fffffffffffffffffffffff204ea3a04ea3ffffffffffffffffffffffffffffffffffffffffffffffff804fa3050a3fff
fffffffffffffffffffffffffffffffffffffffffffffe050a36051a3ffffffffffffffffffffffffffffffffffffffff
ffffffff4052a3c052a3ffffffffffffffffffffffffffffffffffffffffffffffffa053a32054a3fffffffffffffffff
fffffffffffffffffffffffffffffff055a38055a3ffffffffffffffffffffffffffffffffffffffffffffffff6056a3e
056a3ffffffffffffffffffffffffffffffffffffffffffffffffc057a34058a3ffffffffffffffffffffffffffffffff
ffffffffffffffff
The random data appears to always be in the same position, but the values vary each time. I am assuming I am running into some issue with incorrectly assign pointers but as of now I am stumped as to what could be causing it.