Ç - 恰好指针数组什么当数组被释放? [英] C - What happens to an array of pointers when the array is freed?

查看:96
本文介绍了Ç - 恰好指针数组什么当数组被释放?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前编程C,和我创建的指针数组。这些包含在数组中的指针将持续整个程序的持续时间。

I am currently programming in C, and I am creating an array of pointers. These pointers contained in the array will last for the duration of the entire program.

假设指针数组是数组A.然后创建指针的B另一个数组,我把数组A到B.数组的元素。然后,我免费阵列A

Let's say the array of pointers is array A. I then create another array of pointers B, and I put an element of array A into array B. Then, I free array A.

会发生什么数组B中的元素?这将不再是有效的,因为数组A已被释放,还是会仍然是有效的,因为实际的指针仍然有效内存?

What will happen to the element in array B? Will it no longer be valid since array A has been freed, or will it still be valid, since the actual pointer is still valid in memory?

感谢

下面是一个什么样我的code看起来像一个例子 -

Here's an example of what my code will look like--

int a = 1;
int b = 2;
int c = 3;

int **array_a = (int **) malloc (sizeof (int *) * 3);
array_a[0] = &a;
array_a[1] = &b;
array_a[2] = &c;

int **array_b = (int **) malloc (sizeof (int *) * 1);
array_b[0] = array_a[0];
free(array_a);

现在,会发生什么array_b [0]?

Now, what happens to array_b[0]?

推荐答案

如果你做到这一点。

int *a = malloc(10 * sizeof(int));
for (int i = 0 ; i != 10 ; i++) {
    a[i] = 2*i+1;
}
int *b = a;
free(a);

然后 B 将是无效的,因为好。

如果你这样做,但是

int *a = malloc(10 * sizeof(int));
for (int i = 0 ; i != 10 ; i++) {
    a[i] = 2*i+1;
}
int *b = malloc(10 * sizeof(int));
memcpy(b, a, 10 * sizeof(int));
free(a);

然后 B 仍然有效。

这篇关于Ç - 恰好指针数组什么当数组被释放?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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