释放一个双指针 [英] free a double pointer

查看:167
本文介绍了释放一个双指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建使用双指针这样的2-D矩阵:

I created a 2-D matrix using double pointer like that:

int** pt; pt = (int*) malloc(sizeof(int)*10);

我知道,指针被释放像

I know that a pointer is freed like that

free(ptr);

我们如何能够释放双指针?

How can we free the double pointer?

如果我们打印的东西,后来被释放内存和退出程序是什么?并最终由内存那我们使用,否则就会是一样的初始?

What if we print something and later freed that memory and exit the program? Does the final memory consist of that which we used or it will be same as initial?

推荐答案

假设你有一个矩阵

int** mat = malloc(10 * sizeof(int*));
for (int i=0; i<10; ++i) {
  mat[i] = malloc(10 * sizeof(int));
}

然后就可以释放矩阵的每一行(假设你已经正确初始化各事前):

then you can free each row of the matrix (assuming you have initialized each correctly beforehand):

for (i=0; i<10; ++i) {
  free(mat[i]);
}

然后释放顶层指针:

then free the top-level pointer:

free(mat);

有关你的第二个问题:如果您分配内存并使用它,你就会改变内存,这将不会是还原,即使你释放它(尽管你将不能够可靠地/访问可移植了)

For your second question: if you allocate memory and use it, you will change that memory, which will not be "reverted" even if you free it (although you will not be able to access it reliably/portably any more).

注意的:顶级的malloc使用的sizeof(INT *)为你分配指针到 - INT S,不是 INT 秒 - 的为int * 和<$大小C $ C> INT 不能保证是相同的。

Note: the top-level malloc is using sizeof(int*) as you are allocating pointer-to-ints, not ints -- the size of int* and int are not guaranteed to be the same

这篇关于释放一个双指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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