如何在for循环中将malloc/free用于2D指针? [英] How to use malloc/free for a 2D pointer in the for loop?

查看:166
本文介绍了如何在for循环中将malloc/free用于2D指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个由** ptr之类的指针定义的2D数组.

我需要使用malloc为它分配内存(** ptr). ** ptr在for循环内使用.什么时候需要在此** ptr中使用malloc/free,在for循环内还是在for循环外?为什么?


非常感谢Advanced.

Hi,

I have a 2D array definded by pointer like ** ptr.

I need to use malloc to allocate memory to it (**ptr). **ptr is used inside a for loop. When should I need to use malloc/free for this **ptr, inside for loop or outside for loop? Why?


Thanks very much in advanced.

推荐答案

您可以根据对分配的内存执行的操作来释放分配的内存,如果该操作在循环内完成,则继续进行并释放它.如果您关注可变的分配长度,请尝试在循环外部定义空缓冲区,并在循环内部使用具有特定长度的realloc.然后,您可以在循环外释放它(视情况而定).例如:-
You can free allocated memory based on the operations you are doing on the allocated memory, if the operation finishes inside the loop then go ahead and free it. If you are concerned with variable length of allocation, try to define null buffer outside the loop and use realloc inside the loop with specific length. Then you can free it outside the loop(as the case may be). Eg:-
char * buffer = NULL;
for (int i = 0; i < 100; i++) {
    buffer = realloc(specific_length_int);
    // do some things with buffer
}
free(buffer);


何时?只有您可以回答该问题,因为只有您知道该程序的要求.您可以在需要使用内存的时间和地点分配内存,并在不再需要内存时将其释放.有时您需要在循环内,有时在外部.没有更多详细的问题,就不可能更精确.
When? Only you can answer that question, as only you know the requirements of the program. You allocate memory when and where you need to use it, and you free it when you no longer need it. Sometimes you will need to do that inside a loop and sometimes outside. Without a lot more detail of your problem it is impossible to be more precise.


malloc()函数分配大小字节,并a pointer返回给已分配的内存.内存未初始化.如果size为0,则malloc()返回NULL或一个唯一的指针值,该值以后可以成功传递给free().​​
所以你就是这样:
The malloc() function allocates size bytes and returns a pointer to the allocated memory. The memory is not initialized. If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().
So you just do it like this:
char** ptr=(char**)malloc(100);
free(ptr);


Don''t think inside loop or outside loop, It''s just a address of memory!


Don''t think inside loop or outside loop, It''s just a address of memory!


这篇关于如何在for循环中将malloc/free用于2D指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆