C free()例程和递增的数组指针 [英] C free() routine and incremented array pointers
本文介绍了C free()例程和递增的数组指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我动态分配一个数组然后传递(不是初始指针,而是指向数组中间的指针),free()
例程会工作吗?示例:
Will the free()
routine work if I dynamically allocate an array and then pass, not the initial pointer, but a pointer to the middle of the array? Example:
int* array = malloc(10 * sizeof *array);
if(array) {
array += 5; // adjusting the indicies
free(array);
}
还是在调用free()
之前需要将指针设置回数组的开头?
Or do I need to set the pointer back to the start of the array before calling free()
?
推荐答案
绝对不是.传递给free()
的值必须与malloc()
返回的值完全相同.实际上,为确保这种情况,我建议您使用指针的副本,如果您需要可以增加或修改的指针.
Absolutely not. The value passed to free()
must be exactly the same value returned by malloc()
. In fact, to ensure this is the case, I would recommend you use a copy of the pointer if you need a pointer you can increment or otherwise modify.
这篇关于C free()例程和递增的数组指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文