我有一個簡單的結構:創建對象:在值類型對象內動態分配數據的指針 - 好還是不好?
typedef struct {
int width, height;
unsigned char *pixels;
} image;
哪一個是更好的API?
image *imagecreate(int w, int h) {
image *img = malloc(sizeof(image));
img->width = w;
img->height = h;
img->pixels = calloc(w * h, 3);
return img;
}
void imagefree(image *img) {
free(img->pixels);
free(img);
}
或
image imagecreate(int w, int h) {
image img;
img.width = w;
img.height = h;
img.pixels = calloc(w * h, 3);
return img;
}
void imagefree(image *img) {
free(img->pixels);
img->width = img->height = 0;
}
?
這似乎是矯枉過正做一個額外的malloc()這樣的小結構是隻有大約一個指向真正的動態分配數據的包裝。但另一方面,在一個值類型中隱藏一個指向動態分配內存的指針感覺不自然(對我來說)。有人可能會認爲你不必釋放它。
你說服了我。我可能會使用指針返回值版本。 – ChrG 2012-04-17 11:59:02