I have this function which has to return a pointer to a 1-dimension array of various (65,535 for this picture) structs. But it returns only the first element of this array, and I am curious what the problem is.
struct pixel* make_pixel (int red, int green, int blue){
struct pixel* pix = malloc(sizeof(struct pixel));
pix->blue = blue;
pix->red = red;
pix->green = green;
return (pix);
}
struct pixel* read_data(FILE *stream, const struct bmp_header *header) {
if(stream == NULL || header == NULL) return 0;
struct pixel *pix = malloc(sizeof(struct pixel));
struct pixel *data[header->width * header->height]; //would be great to do this dynamically
for (int i = 0; i < (header->width * header->height); i++) {
fread(pix, sizeof(struct pixel), 1, stream); //reads pixels 1 by 1 from stream
data[i] = make_pixel(pix->red, pix->green, pix->blue); //put pixel as an i'th element of 'data' array
}
free(pix);
return (*data);
}
int main() {
const char* fileName = "C:/TheWaaay.../assets/lenna.bmp";
FILE* image = fopen(fileName, "rb");
struct bmp_header *header = read_bmp_header(image);
struct pixel *data = read_data(image, header);
return 1;
}
The structure of actual pixel:
struct pixel {
uint8_t blue;
uint8_t green;
uint8_t red;
//uint8_t alpha;
} __attribute__((__packed__));
You should make data
be a pointer to pointers, and return that.
struct pixel **read_data(FILE *stream, const struct bmp_header *header) {
if(stream == NULL || header == NULL) return 0;
struct pixel *pix;
struct pixel **data;
pix = malloc(sizeof *pix);
data = malloc(header->width * header->height * sizeof *data);
for (int i = 0; i < header->width * header->height; i++) {
fread(pix, sizeof(struct pixel), 1, stream);
data[i] = make_pixel(pix->red, pix->green, pix->blue);
}
free(pix);
return data;
}
main
would become:
int main() {
const char* fileName = "C:/TheWaaay.../assets/lenna.bmp";
FILE* image = fopen(fileName, "rb");
struct bmp_header *header = read_bmp_header(image);
struct pixel **data = read_data(image, header);
for(int i = 0; i < header->width * header->height; i++) {
// do something here with data[i]
struct pixel *pix = data[i];
// manipulate pix, which points to data[i]
}
return 1;
}
data
is an array of pointers, not an array of pixels. You can allocate an array of pixels dynamically, and read directly into that.
struct pixel* read_data(FILE *stream, const struct bmp_header *header) {
if(stream == NULL || header == NULL) return 0;
struct pixel *data = malloc(header->width * header->height * sizeof(struct pixel));
if (data == NULL) {
return NULL;
}
fread(&pixel[i], sizeof(struct pixel), header->width * header->height, stream);
return data;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.