Free()如何与堆栈上包含在堆上制造的阵列的结构进行交互?
假设我想创建一个包含图像数据的新结构
struct Image {
int *pxl_arr;
int pxl_arr_len;
int img_wdt, img_hgt;
};
,并且我还具有单独的函数,该功能打开图像文件并将文件的内容复制到使用Malloc()上在堆上制造的整数中可以解析该数据并将其与struct Image
一起使用,
int *freadarr (char *fpath) {
FILE *fptr;
long len;
int *buf;
/* code to open file here */
buf = (int *) malloc(len);
/* code to read from file here */
return buf;
}
然后在main()
函数的内部,我要这样做:
int main() {
struct Image img;
img.pxl_arr = freadarr(/* whatever the file path is */);
free(img);
return 0;
}
什么将free()使用
结构图像
?
编辑:img.pxl_arr
,不是img-> pxl_arr
Say I want to create a new struct that contains image data
struct Image {
int *pxl_arr;
int pxl_arr_len;
int img_wdt, img_hgt;
};
And I also had a separate function that opened an image file and copied the contents of the file into an array of integers made on the heap using malloc(), so that some other function could parse that data and use it with the struct Image
int *freadarr (char *fpath) {
FILE *fptr;
long len;
int *buf;
/* code to open file here */
buf = (int *) malloc(len);
/* code to read from file here */
return buf;
}
Then inside of the main()
function, I were to do this:
int main() {
struct Image img;
img.pxl_arr = freadarr(/* whatever the file path is */);
free(img);
return 0;
}
What would free()
do with the struct Image
?
EDIT: img.pxl_arr
, not img->pxl_arr
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
没什么,因为您只能传递到
免费
从malloc
返回的任何指针值(或calloc
/realloc
),或null
。在您的(略有缺陷)示例中,这将是结构的pxl_arr
持有的值。也许任何,因为传递任何其他值是不确定的行为< /a>,但是您的编译器应大声投诉
free(img);
:将指针值传递给
免费
完成后:请注意,请注意
- &gt;
用于通过指针访问结构的成员。img
不是指针,因此请使用。
操作员。请参阅:成员访问操作员Nothing, as you should only pass to
free
any pointer value returned frommalloc
(orcalloc
/realloc
), orNULL
. In your (slightly flawed) example, that would be the value held by thepxl_arr
member of the structure.Or maybe anything, as passing any other value is Undefined Behaviour, but your compiler should complain loudly about
free(img);
:Pass the pointer value to
free
when you are done with it:Note that
->
is for accessing the members of a structure via a pointer.img
is not a pointer, so use the.
operator. See: Member access operatorsfree(struct)
用于释放(hehe)已重新记录到struct
的内存。在这种情况下,您将丢失
struct Image
内部的信息,这意味着一个指针和2个整数,并且仅当struct Image
已使用malloc(malloc)( )
。free(struct)
is use to free (hehe) the memory that have been recerved tostruct
.In this case you will lose the info inside
struct Image
, that means one Pointer and 2 Integers, if and only if thestruct Image
have been recerved withmalloc()
.