Click here to Skip to main content
11,502,547 members (39,340 online)
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C++ C VC
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;
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 27-Dec-12 7:55am

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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;
  Permalink  
Comments
Pravinda Amarathunge at 27-Dec-12 14:21pm
   
Thks, Will this work fine without leaks ?
André Kraak at 27-Dec-12 14:27pm
   
Yes, just remember that at the end you still need to use free( data );
Pravinda Amarathunge at 27-Dec-12 15:18pm
   
can't use data=newData. But 'memcpy' works fine !
Mohibur Rashid at 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)



Advertise | Privacy | Mobile
Web04 | 2.8.150520.1 | Last Updated 27 Dec 2012
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100