[英]C usage of malloc on struct
我正在嘗試在名為image的結構上使用malloc。 該函數是:
void image_init(struct image* img, int w, int h) {
img = malloc(sizeof(struct image));
(*img).w = w;
(*img).h = h;
}
再次釋放圖像的功能是:
void image_destroy(struct image* img) {
free(img);
}
但是,每當我嘗試釋放由malloc分配的數據時,我都會得到一個錯誤,即我嘗試釋放的地址之前沒有進行malloc分配。
圖像的結構為:
struct image {
int w,h;
int* data;
}
我用以下函數調用這些函數:
struct image img;
image_init(&img,100,100);
image_destroy(&img);
首先在這里
void image_init(struct image* img, int w, int h) {
img = malloc(sizeof(struct image));
(*img).w = w;
(*img).h = h;
}
img
是傳遞給它的原始指針的副本 ,因此函數內第一行的代碼無效,因為它使復制點指向某個位置-而不是原始對象。
這個:
struct image img;
image_init(&img,100,100);
image_destroy(&img);
也沒有任何意義(假設您希望img
在調用init
之后指向某處)。 img
不是指針,您如何期望它指向某個地方?
解決這個問題的一種方法可能是
struct image *img = image_init(100,100);
哪里
struct image* image_init(int w, int h) {
img = malloc(sizeof(struct image));
(*img).data = NULL;
(*img).w = w;
(*img).h = h;
return img;
}
不要忘了打電話給free
對上述函數返回的指針-你需要免費data
指針分開過,在你分配太案件。
注意 :我最好的猜測(如果您也不能更改原型)是您想要這樣的東西:
void image_init(struct image* img, int w, int h) {
img->data = malloc(sizeof(int) * w * h);
img->w = w;
img->h = h;
}
破壞:
void image_destroy(struct image* img) {
free(img->data);
free(img);
}
在主要
struct image* img = malloc(sizeof(struct image));
image_init(img, 100, 100);
image_destroy(img);
PS。 或者,如果您希望保留這些功能的用法,就像您對Johnny Mopp的回答一樣。
我認為您的任務不是分配img
而是分配data
ptr:
void image_init(struct image* img, int w, int h) {
img->data = malloc(sizeof(int) * w * h);// Check for failure...
img->w = w;
img->h = h;
}
void image_destroy(struct image* img) {
free(img->data);
}
struct image img;
image_init(&img,100,100);
image_destroy(&img);
在堆棧上分配圖像結構。 您為什么要嘗試分配一個? 如果您真的想要一個堆,那就去做
struct image * image_init( int w, int h) {
struct image *img = malloc(sizeof(struct image));
img->w = w;
img->h = h;
return img;
}
...
struct image *img = image_init(100,100);
注意更多慣用的“->”用法
如果您想將其放在堆棧上,請執行
void image_init(struct image* img, int w, int h) {
img->w = w;
img->h = h;
}
您需要將malloc強制轉換為struct,因為malloc的返回值是void類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.