Click here to Skip to main content
13,409,451 members (39,900 online)
Rate this:
Please Sign up or sign in to vote.
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 :
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 8:55am

1 solution

Rate this: bad
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;
Pravinda Amarathunge 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 );
Pravinda Amarathunge 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)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web04 | 2.8.180221.1 | Last Updated 27 Dec 2012
Copyright © CodeProject, 1999-2018
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