Click here to Skip to main content
15,901,001 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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 :
C++
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;

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.
Posted

1 solution

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

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

free( data );

data = newData;
newData = null;
 
Share this answer
 
Comments
Captain Price 27-Dec-12 14:21pm    
Thks, Will this work fine without leaks ?
André Kraak 27-Dec-12 14:27pm    
Yes, just remember that at the end you still need to use free( data );
Captain Price 27-Dec-12 15:18pm    
can't use data=newData. But 'memcpy' works fine !
Mohibur Rashid 27-Dec-12 21:43pm    
in that case you still would have memory problem. memcpy might work but it would lead you to corrupted data.

and data=newData must have to work, make sure both of your data and newData are (int *)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900