从位于Dynamic数组中间的内存中释放一些值。 [英] Free some values from memory located in the middle of a Dynamic array.

查看:65
本文介绍了从位于Dynamic数组中间的内存中释放一些值。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个动态分配的数组,类型为 int ,名为 data 。我用3 int s分配了它,并为它们分配了如下值。

代码:

I''ve got a dynamically allocated array of type int called data. I allocated it with 3 ints, and assigned them some values as below.
Code :

int * data = (int *) malloc(sizeof(int) * 3); //Now there are 3 elements in the array 'data'.

//Assigning values
data[0] = 1;
data[1] = 2;
data[2] = 3;



问题:

现在,我要删除 data [1] 免费它,然后加入数组的其他2部分( data [0] [data2] )并最终得到一个指向新数组的指针。


Problem :
Now, I want to delete data[1], free it, then join the other 2 parts of array (data[0] and [data2]) and finally get a pointer to the new array.

推荐答案

一种方法是:

One way to do it is:
int * newData = (int *) malloc(sizeof(int) * 2);

newData[0] = data[0];
newData[1] = data[2];

free( data );

data = newData;
newData = null;


这篇关于从位于Dynamic数组中间的内存中释放一些值。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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