簡體   English   中英

我如何返回指向一維結構 function 的指針,其中包含各種結構?

[英]How do i return a pointer to a 1 dimension struct function with a various structs inside?

我有這個 function ,它必須返回一個指向各種(這張圖片為 65,535)結構的一維數組的指針。 但它只返回這個數組的第一個元素,我很好奇問題出在哪里。

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;
}

實際像素的結構:

struct pixel {
    uint8_t blue;
    uint8_t green;
    uint8_t red;
    //uint8_t alpha;
} __attribute__((__packed__));

您應該使data成為指向指針的指針,並返回它。

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將變為:

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是指針數組,而不是像素數組。 您可以動態分配像素數組,然后直接讀取。

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM