指针的最佳实践 [英] Pointer best practice
问题描述
我刚开始学习C和奋斗的指针(当然):)
I am just starting to learn C and (of course) struggling with pointers :)
由于这个片段:
int *storage, *storage_p;
storage = malloc(sizeof(int[GROW_BY]));
storage_p = storage;
// do something with storage, using storage_p
free(storage);
storage = NULL;
是否真正有必要申报与 malloc的工作两个变量()
编数据?它是很好的做法,创建一个存储
和 storage_p
我做的方法是什么?如果不是,那会是'方式'?
Is it really necessary to have two variables declared to work with the malloc()
'ed data? Is it good practice to create a storage
and storage_p
the way I did? If not, what would would be 'the way'?
推荐答案
您将需要一个指针,将举行由malloc(返回的值),这样您可以稍后释放它。
You will need a pointer that will hold the value returned by malloc(), so that you can free it later.
如果您计划使用storage_p的是要改变它的价值是什么,那么你将需要两个指针。
If what you plan on using storage_p for is going to change it value, then you are going to need two pointers.
不过,我一般保持纯粹的初始指针,并创建新的,临时的,因为我需要的。
However, I generally keep the pure initial pointer, and create new ones, ad hoc, as I need one.
int *storage = (int*) malloc(sizeof(int[GROW_BY]));
// :
int* ptr = storage;
while (*ptr)
{
// :
++ptr;
}
这篇关于指针的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!