Click here to Skip to main content
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)

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 839
1 OriginalGriff 400
2 CPallini 275
3 George Jonsson 191
4 Richard Deeming 145
0 OriginalGriff 5,450
1 Sergey Alexandrovich Kryukov 4,532
2 CPallini 4,500
3 George Jonsson 3,102
4 Gihan Liyanage 2,445


Advertise | Privacy | Mobile
Web02 | 2.8.140916.1 | Last Updated 27 Dec 2012
Copyright © CodeProject, 1999-2014
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